]> git.p6c8.net - psmysqlbackup.git/blob - psmysqlbackup.ps1
Allow to define databases to exclude from backup
[psmysqlbackup.git] / psmysqlbackup.ps1
1 [String]$configMysqlHost = "localhost"
2 [Int32]$configMysqlPort = 3306
3 [String]$configMysqlUser = "backup"
4 [String]$configMysqlPassword = "backup"
5
6 [String]$configMysqlCli = "C:\Program Files\MariaDB 10.5\bin\mysql.exe"
7 [String]$configMysqldumpCli = "C:\Program Files\MariaDB 10.5\bin\mysqldump.exe"
8
9 [String]$configBackupDir = "backup"
10 [Int32]$configRotate = 7
11
12 [String]$configDbExclusions = @("test")
13
14 $defaultExclusions = @("information_schema", "performance_schema")
15
16 function Get-Databases() {
17 $databaseString = (& $configMysqlCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --batch --skip-column-names -e "SHOW DATABASES;")
18 $databases = $databaseString.split([Environment]::NewLine)
19
20 return $databases
21 }
22
23 function Create-Backup([String]$database, [String]$target) {
24 & $configMysqldumpCli --host=$configMysqlHost --port=$configMysqlPort --user=$configMysqlUser --password=$configMysqlPassword --single-transaction --result-file=$target $database
25 }
26
27 function Rotate-Backups($backupDir) {
28 if($configRotate -le 0) {
29 return
30 }
31
32 $keepBackupsCount = $configRotate
33
34 Get-ChildItem $backupDir -File | Where-Object {($_.Name -match "^backup-.+-\d{8,}-\d{6}\.sql$")} | Sort-Object -Descending |
35 Foreach-Object {
36 if($keepBackupsCount -ge 0) {
37 $keepBackupsCount--
38 }
39
40 if($keepBackupsCount -eq -1) {
41 Write-Output "Deleting backup $($_.FullName)"
42 Remove-Item -Force $_.FullName
43 }
44 }
45 }
46
47 $currDaytime = Get-Date -format "yyyyMMdd-HHmmss"
48
49 $databases = Get-Databases | Where-Object {!($_ -in $defaultExclusions -or $_ -in $configDbExclusions)}
50
51 foreach($d in $databases) {
52 $databaseBackupDir = Join-Path -Path $configBackupDir -ChildPath $d
53
54 if(!(Test-Path $databaseBackupDir)) {
55 New-Item -ItemType directory -Path $databaseBackupDir -ErrorAction Stop | Out-Null
56 }
57
58 $databaseBackupFile = Join-Path -Path $databaseBackupDir -ChildPath "backup-$d-$currDaytime.sql"
59 Write-Output "Backing up $d to $databaseBackupFile..."
60 Create-Backup $d $databaseBackupFile
61 Rotate-Backups $databaseBackupDir
62 }

patrick-canterino.de