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/psmysqlbackup
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")
24 $configDbExcludePattern = @()
28 function Get-Databases() {
29 $databaseString = (& $configMysqlCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --batch --skip-column-names -e "SHOW DATABASES;")
31 if($LastExitCode -ne 0) {
32 throw "MySQL CLI exited with Exit code $LastExitCode"
35 $databases = $databaseString.split([Environment]::NewLine)
40 function Create-Backup([String]$database, [String]$target) {
41 & $configMysqldumpCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --single-transaction --result-file=$target $database
43 if($LastExitCode -ne 0) {
44 throw "mysqldump exited with Exit code $LastExitCode"
48 function Rotate-Backups($backupDir) {
49 if($configRotate -le 0) {
53 $keepBackupsCount = $configRotate
55 Get-ChildItem $backupDir -File | Where-Object {($_.Name -match "^backup-.+-\d{8,}-\d{6}\.sql$")} | Sort-Object -Descending |
57 if($keepBackupsCount -ge 0) {
61 if($keepBackupsCount -eq -1) {
62 Write-Output "Deleting backup $($_.FullName)"
63 Remove-Item -Force $_.FullName
68 $defaultDbExclude = @("information_schema", "performance_schema")
70 $currDaytime = Get-Date -format "yyyyMMdd-HHmmss"
73 $databases = Get-Databases | Where-Object {!($_ -in $defaultDbExclude)}
76 Write-Output "Failed to get list of databases"
81 $databasesToBackup = @()
83 if($configDbBackup -and $configDbBackup.count -gt 0) {
84 foreach($cDb in $configDbBackup) {
85 if($cDb -in $databases) {
86 $databasesToBackup += $cDb
89 Write-Warning "Not backing up database $cDb, because it does not exist"
94 :excludeOuter foreach($rDb in $databases) {
95 if($rDb -in $configDbExclude) {
99 foreach($cPattern in $configDbExcludePattern) {
100 if($rDb -match $cPattern) {
101 continue excludeOuter;
105 $databasesToBackup += $rDb
109 foreach($d in $databasesToBackup) {
110 $databaseBackupDir = Join-Path -Path $configBackupDir -ChildPath $d
112 if(!(Test-Path $databaseBackupDir)) {
113 New-Item -ItemType directory -Path $databaseBackupDir -ErrorAction Stop | Out-Null
116 $databaseBackupFile = Join-Path -Path $databaseBackupDir -ChildPath "backup-$d-$currDaytime.sql"
117 Write-Output "Backing up $d to $databaseBackupFile..."
120 Create-Backup $d $databaseBackupFile
121 Rotate-Backups $databaseBackupDir
124 Write-Output "Could not backup database $d to $databaseBackupFile"