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 $configDbExclude = @("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 $defaultDbExclude = @("information_schema", "performance_schema")
69 $currDaytime = Get-Date -format "yyyyMMdd-HHmmss"
72 $databases = Get-Databases | Where-Object {!($_ -in $defaultDbExclude -or $_ -in $configDbExclude)}
75 Write-Output "Failed to get list of databases"
80 $databasesToBackup = @()
82 if($configDbBackup -and $configDbBackup.count -gt 0) {
83 foreach($cDb in $configDbBackup) {
84 if($cDb -in $databases) {
85 $databasesToBackup += $cDb
88 Write-Warning "Not backing up database $cDb, because it does not exist"
93 $databasesToBackup = $databases
96 foreach($d in $databasesToBackup) {
97 $databaseBackupDir = Join-Path -Path $configBackupDir -ChildPath $d
99 if(!(Test-Path $databaseBackupDir)) {
100 New-Item -ItemType directory -Path $databaseBackupDir -ErrorAction Stop | Out-Null
103 $databaseBackupFile = Join-Path -Path $databaseBackupDir -ChildPath "backup-$d-$currDaytime.sql"
104 Write-Output "Backing up $d to $databaseBackupFile..."
107 Create-Backup $d $databaseBackupFile
108 Rotate-Backups $databaseBackupDir
111 Write-Output "Could not backup database $d to $databaseBackupFile"