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

patrick-canterino.de