Бэкап MySQL через mysqldump
Создаёт согласованный дамп баз MySQL в новый каталог и проверяет код возврата.
Что делает скрипт
Скрипт вызывает mysqldump с single-transaction и quick, не передавая пароль в аргументах. Учётные данные берутся из defaults-extra-file или клиентской конфигурации. Каждый дамп пишется в новый файл, после чего создаётся CSV manifest.
- Для доступа нужен пользователь с правами на дамп, пароль храните в защищённом файле.
Быстрый старт
powershell -File Backup-MySQL.ps1 -Database app,shop -Destination E:\Backup\MySQL -DefaultsFile C:\secure\mysql-backup.cnf
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Backup-MySQL.ps1 -Database app -Destination E:\Backup\MySQL -DefaultsFile C:\secure\mysql-backup.cnfpowershell -File Backup-MySQL.ps1 -Database app,shop -Destination E:\Backup\MySQL -DryRun
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
winget install Oracle.MySQL
Backup-MySQL.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string[]]$Database,
[Parameter(Mandatory = $true)]
[string]$Destination,
[string]$DbUser = 'backup',
[string]$DbHost = '127.0.0.1',
[int]$Port = 3306,
[string]$DefaultsFile,
[switch]$DryRun
)
$ErrorActionPreference = 'Stop'
$dumpCommand = Get-Command mysqldump -ErrorAction SilentlyContinue
if (-not $dumpCommand) {
throw 'mysqldump not found. Install MySQL client tools.'
}
$destFull = [System.IO.Path]::GetFullPath($Destination)
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$targetRoot = Join-Path $destFull ('mysql-' + $stamp)
$defaultsPath = ''
if (-not [string]::IsNullOrWhiteSpace($DefaultsFile)) {
$defaultsPath = [System.IO.Path]::GetFullPath($DefaultsFile)
if (-not (Test-Path -LiteralPath $defaultsPath -PathType Leaf)) {
throw "Defaults file not found: $defaultsPath"
}
}
if (Test-Path -LiteralPath $targetRoot) {
throw "Destination already exists: $targetRoot"
}
if (-not $DryRun) {
New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null
}
$manifest = New-Object System.Collections.Generic.List[object]
$total = 0
foreach ($name in $Database) {
if ([string]::IsNullOrWhiteSpace($name)) { continue }
$safeName = $name -replace '[^A-Za-z0-9._-]', '_'
$target = Join-Path $targetRoot ($safeName + '.sql')
if (Test-Path -LiteralPath $target) {
throw "Dump already exists: $target"
}
$dumpArgs = @()
if ($defaultsPath) {
$dumpArgs += "--defaults-extra-file=$defaultsPath"
}
$dumpArgs += @(
'--single-transaction',
'--quick',
'--routines',
'--triggers',
'--events',
'--host', $DbHost,
'--port', "$Port",
'--user', $DbUser,
'--databases', $name
)
if ($DryRun) {
$display = ($dumpArgs | ForEach-Object { '"' + $_ + '"' }) -join ' '
Write-Host "mysqldump $display > $target"
continue
}
$quoted = ($dumpArgs | ForEach-Object { '"' + ($_ -replace '"', '\"') + '"' }) -join ' '
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = $dumpCommand.Source
$startInfo.Arguments = $quoted
$startInfo.UseShellExecute = $false
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$startInfo.CreateNoWindow = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$stream = [System.IO.File]::Open($target, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write)
try {
$process.Start() | Out-Null
$errorTask = $process.StandardError.ReadToEndAsync()
$process.StandardOutput.BaseStream.CopyTo($stream)
$stream.Close()
$process.WaitForExit()
$errorText = $errorTask.Result
} catch {
$stream.Close()
if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Force }
throw
}
if ($process.ExitCode -ne 0) {
Remove-Item -LiteralPath $target -Force
throw "mysqldump failed for $name with code $($process.ExitCode): $errorText"
}
$manifest.Add([pscustomobject]@{
Database = $name
File = $target
Length = (Get-Item -LiteralPath $target).Length
SHA256 = (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash
})
$total++
Write-Host "Dumped: $name"
}
if (-not $DryRun) {
$manifestPath = Join-Path $targetRoot 'manifest.csv'
if ($manifest.Count -gt 0) {
$manifest | Export-Csv -LiteralPath $manifestPath -NoTypeInformation -Encoding UTF8
} else {
Set-Content -LiteralPath $manifestPath -Value 'Database,File,Length,SHA256' -Encoding UTF8
}
Write-Host "Databases: $total"
Write-Host "Folder: $targetRoot"
}
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.