2 # PowerShell script for backing up MySQL / MariaDB databases on Windows
4 # Author: Patrick Canterino <patrick@patrick-canterino.de>
5 # WWW: https://www.patrick-canterino.de/
6 # https://github.com/pcanterino/dsmonrot
7 # License: 2-Clause BSD License
11 $configMysqlHost = "localhost"
12 $configMysqlPort = 3306
13 $configMysqlUser = "backup"
14 $configMysqlPassword = "backup"
16 $configMysqlCli = "C:\Program Files\MariaDB 10.5\bin\mysql.exe"
17 $configMysqldumpCli = "C:\Program Files\MariaDB 10.5\bin\mysqldump.exe"
19 $configBackupDir = "backup"
23 $configDbExclusions = @("test")
27 function Get-Databases() {
28 $databaseString = (& $configMysqlCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --batch --skip-column-names -e "SHOW DATABASES;")
30 if($LastExitCode -ne 0) {
31 throw "MySQL CLI exited with Exit code $LastExitCode"
34 $databases = $databaseString.split([Environment]::NewLine)
39 function Create-Backup([String]$database, [String]$target) {
40 & $configMysqldumpCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --single-transaction --result-file=$target $database
42 if($LastExitCode -ne 0) {
43 throw "mysqldump exited with Exit code $LastExitCode"
47 function Rotate-Backups($backupDir) {
48 if($configRotate -le 0) {
52 $keepBackupsCount = $configRotate
54 Get-ChildItem $backupDir -File | Where-Object {($_.Name -match "^backup-.+-\d{8,}-\d{6}\.sql$")} | Sort-Object -Descending |
56 if($keepBackupsCount -ge 0) {
60 if($keepBackupsCount -eq -1) {
61 Write-Output "Deleting backup $($_.FullName)"
62 Remove-Item -Force $_.FullName
67 $defaultExclusions = @("information_schema", "performance_schema")
69 $currDaytime = Get-Date -format "yyyyMMdd-HHmmss"
72 $databases = Get-Databases | Where-Object {!($_ -in $defaultExclusions -or $_ -in $configDbExclusions)}
75 Write-Output "Failed to get list of databases"
80 $databasesToBackup = @()
82 if($configDbBackup -and $configDbBackup.count -gt 0) {
83 $databasesToBackup = $configDbBackup
86 $databasesToBackup = $databases
89 foreach($d in $databasesToBackup) {
90 $databaseBackupDir = Join-Path -Path $configBackupDir -ChildPath $d
92 if(!(Test-Path $databaseBackupDir)) {
93 New-Item -ItemType directory -Path $databaseBackupDir -ErrorAction Stop | Out-Null
96 $databaseBackupFile = Join-Path -Path $databaseBackupDir -ChildPath "backup-$d-$currDaytime.sql"
97 Write-Output "Backing up $d to $databaseBackupFile..."
100 Create-Backup $d $databaseBackupFile
101 Rotate-Backups $databaseBackupDir
104 Write-Output "Could not backup database $d to $databaseBackupFile"