1 [String]$configMysqlHost = "localhost"
2 [Int32]$configMysqlPort = 3306
3 [String]$configMysqlUser = "backup"
4 [String]$configMysqlPassword = "backup"
6 [String]$configMysqlCli = "C:\Program Files\MariaDB 10.5\bin\mysql.exe"
7 [String]$configMysqldumpCli = "C:\Program Files\MariaDB 10.5\bin\mysqldump.exe"
9 [String]$configBackupDir = "backup"
10 [Int32]$configRotate = 7
13 $configDbExclusions = @("test")
15 $defaultExclusions = @("information_schema", "performance_schema")
17 function Get-Databases() {
18 $databaseString = (& $configMysqlCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --batch --skip-column-names -e "SHOW DATABASES;")
19 $databases = $databaseString.split([Environment]::NewLine)
24 function Create-Backup([String]$database, [String]$target) {
25 & $configMysqldumpCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --single-transaction --result-file=$target $database
28 function Rotate-Backups($backupDir) {
29 if($configRotate -le 0) {
33 $keepBackupsCount = $configRotate
35 Get-ChildItem $backupDir -File | Where-Object {($_.Name -match "^backup-.+-\d{8,}-\d{6}\.sql$")} | Sort-Object -Descending |
37 if($keepBackupsCount -ge 0) {
41 if($keepBackupsCount -eq -1) {
42 Write-Output "Deleting backup $($_.FullName)"
43 Remove-Item -Force $_.FullName
48 $currDaytime = Get-Date -format "yyyyMMdd-HHmmss"
50 $databases = Get-Databases | Where-Object {!($_ -in $defaultExclusions -or $_ -in $configDbExclusions)}
52 $databasesToBackup = @()
54 if($configDbBackup -and $configDbBackup.count -gt 0) {
55 $databasesToBackup = $configDbBackup
58 $databasesToBackup = $databases
61 foreach($d in $databasesToBackup) {
62 $databaseBackupDir = Join-Path -Path $configBackupDir -ChildPath $d
64 if(!(Test-Path $databaseBackupDir)) {
65 New-Item -ItemType directory -Path $databaseBackupDir -ErrorAction Stop | Out-Null
68 $databaseBackupFile = Join-Path -Path $databaseBackupDir -ChildPath "backup-$d-$currDaytime.sql"
69 Write-Output "Backing up $d to $databaseBackupFile..."
70 Create-Backup $d $databaseBackupFile
71 Rotate-Backups $databaseBackupDir