3 $configMysqlHost = "localhost"
4 $configMysqlPort = 3306
5 $configMysqlUser = "backup"
6 $configMysqlPassword = "backup"
8 $configMysqlCli = "C:\Program Files\MariaDB 10.5\bin\mysql.exe"
9 $configMysqldumpCli = "C:\Program Files\MariaDB 10.5\bin\mysqldump.exe"
11 $configBackupDir = "backup"
15 $configDbExclusions = @("test")
19 function Get-Databases() {
20 $databaseString = (& $configMysqlCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --batch --skip-column-names -e "SHOW DATABASES;")
22 if($LastExitCode -ne 0) {
23 throw "MySQL CLI exited with Exit code $LastExitCode"
26 $databases = $databaseString.split([Environment]::NewLine)
31 function Create-Backup([String]$database, [String]$target) {
32 & $configMysqldumpCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --single-transaction --result-file=$target $database
34 if($LastExitCode -ne 0) {
35 throw "mysqldump exited with Exit code $LastExitCode"
39 function Rotate-Backups($backupDir) {
40 if($configRotate -le 0) {
44 $keepBackupsCount = $configRotate
46 Get-ChildItem $backupDir -File | Where-Object {($_.Name -match "^backup-.+-\d{8,}-\d{6}\.sql$")} | Sort-Object -Descending |
48 if($keepBackupsCount -ge 0) {
52 if($keepBackupsCount -eq -1) {
53 Write-Output "Deleting backup $($_.FullName)"
54 Remove-Item -Force $_.FullName
59 $defaultExclusions = @("information_schema", "performance_schema")
61 $currDaytime = Get-Date -format "yyyyMMdd-HHmmss"
64 $databases = Get-Databases | Where-Object {!($_ -in $defaultExclusions -or $_ -in $configDbExclusions)}
67 Write-Output "Failed to get list of databases"
72 $databasesToBackup = @()
74 if($configDbBackup -and $configDbBackup.count -gt 0) {
75 $databasesToBackup = $configDbBackup
78 $databasesToBackup = $databases
81 foreach($d in $databasesToBackup) {
82 $databaseBackupDir = Join-Path -Path $configBackupDir -ChildPath $d
84 if(!(Test-Path $databaseBackupDir)) {
85 New-Item -ItemType directory -Path $databaseBackupDir -ErrorAction Stop | Out-Null
88 $databaseBackupFile = Join-Path -Path $databaseBackupDir -ChildPath "backup-$d-$currDaytime.sql"
89 Write-Output "Backing up $d to $databaseBackupFile..."
92 Create-Backup $d $databaseBackupFile
95 Write-Output "Could not backup database $d to $databaseBackupFile"
99 Rotate-Backups $databaseBackupDir