Files
bj_power/sql/backup_pg_databases.ps1
T

103 lines
3.8 KiB
PowerShell
Raw Normal View History

# bj_power PostgreSQL 自动备份脚本(MES + WMS)
#
# 用法:
# 手动执行: powershell -ExecutionPolicy Bypass -File D:\hardman\bj_power\sql\backup_pg_databases.ps1
# 计划任务: 见同目录《备份部署说明.md》(本脚本不自动注册任务)
#
# 行为:
# 1. pg_dump 自定义格式(-Fc)备份 bj_power_mes / bj_power_wms 两库到 backup 目录
# 2. 保留 365 天,超期 .dump 自动清理
# 3. 全程日志写 backup\backup.log;任一库失败 exit 1(供计划任务识别)
param(
# 备份输出根目录(默认项目下 backup\)
[string]$BackupRoot = "D:\hardman\bj_power\backup",
# 保留天数
[int]$RetentionDays = 365,
# PostgreSQL 连接参数
[string]$PgHost = "127.0.0.1",
[int]$PgPort = 5432,
[string]$PgUser = "postgres",
[string]$PgPassword = "postgres",
# 待备份数据库列表
[string[]]$Databases = @("bj_power_mes", "bj_power_wms")
)
$ErrorActionPreference = "Stop"
# ---------- 定位 pg_dump.exe(探测常见安装版本,找不到再报错) ----------
function Find-PgDump {
$candidates = @()
foreach ($ver in 9..17) {
$candidates += "C:\Program Files\PostgreSQL\$ver\bin\pg_dump.exe"
$candidates += "C:\Program Files (x86)\PostgreSQL\$ver\bin\pg_dump.exe"
}
$candidates += "C:\PostgreSQL\bin\pg_dump.exe"
foreach ($p in $candidates) {
if (Test-Path $p) { return $p }
}
# 兜底:PATH 里找
$cmd = Get-Command pg_dump.exe -ErrorAction SilentlyContinue
if ($cmd) { return $cmd.Source }
throw "未找到 pg_dump.exe,请安装 PostgreSQL 客户端工具或修改本脚本显式指定路径"
}
# ---------- 日志 ----------
if (-not (Test-Path $BackupRoot)) {
New-Item -ItemType Directory -Path $BackupRoot -Force | Out-Null
}
$LogFile = Join-Path $BackupRoot "backup.log"
function Write-Log([string]$msg) {
$line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $msg"
Add-Content -Path $LogFile -Value $line -Encoding UTF8
Write-Output $line
}
try {
$pgDump = Find-PgDump
Write-Log "==== 备份开始(pg_dump: $pgDump)===="
# pg_dump 密码经环境变量传入,避免交互提示挂起
$env:PGPASSWORD = $PgPassword
$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$failed = $false
foreach ($db in $Databases) {
$outFile = Join-Path $BackupRoot "${db}_${stamp}.dump"
try {
Write-Log "备份 $db -> $outFile"
& $pgDump -h $PgHost -p $PgPort -U $PgUser -d $db -Fc -f $outFile
if ($LASTEXITCODE -ne 0) { throw "pg_dump 退出码 $LASTEXITCODE" }
$size = (Get-Item $outFile).Length
Write-Log "备份完成 $db($([math]::Round($size / 1MB, 2)) MB)"
} catch {
$failed = $true
Write-Log "备份失败 $db:$($_.Exception.Message)"
if (Test-Path $outFile) { Remove-Item $outFile -Force }
}
}
# ---------- 超期清理:保留 RetentionDays 天 ----------
$cutoff = (Get-Date).AddDays(-$RetentionDays)
$old = Get-ChildItem -Path $BackupRoot -Filter "*.dump" -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -lt $cutoff }
foreach ($f in $old) {
try {
Remove-Item $f.FullName -Force
Write-Log "已清理超期备份 $($f.Name)($($f.LastWriteTime.ToString('yyyy-MM-dd')))"
} catch {
Write-Log "清理失败 $($f.Name):$($_.Exception.Message)"
}
}
Write-Log "==== 备份结束($(if ($failed) { '存在失败' } else { '全部成功' }))===="
if ($failed) { exit 1 }
exit 0
} catch {
Write-Log "备份脚本异常终止:$($_.Exception.Message)"
exit 1
} finally {
Remove-Item Env:PGPASSWORD -ErrorAction SilentlyContinue
}