我需要为数据库逻辑转储创建一个简单的脚本。使用脚本有两个目的。
我想检查pg_dump
循环内每个命令开始(foreach
)的错误代码,记录并继续。
最好的方法是什么?
到目前为止,我发现我可以使用try
和catch
。
旁注:在我的代码中,出于测试目的,我仅尝试try..catch
一次。
$path = '"C:\Program Files\PostgreSQL\version\bin\pg_dump.exe"'
$backup_path = 'D:\Backups\test\'
$limit = (Get-Date).AddDays(-2)
$logdate = (Get-Date).ToString("yyyy-MM-dd")
$pg_suffix = "pg_dump"
#$LogFile = $backup_path\$pg_suffix_$(Get-Date -f yyyy-MM-dd) + '.log'
$pg_dump_error = "pg_dump has failed"
$p = $args
[array]$DB_Array = @('postgres', 'db02', 'db03')
if ($p -ne $null) {
try {
foreach ($DB in $p) {
$backup_path_temp = $backup_path + $DB + '_' + $(Get-Date -f yyyy-MM-dd) + '.backup'
cmd /c "$path -w -h localhost -U postgres -Z3 -Fd -j 12 -f $backup_path_temp $DB"
}
} catch {
#"Error! $pg_dump_error" | Tee-Object -FilePath $LogFile -Append | Write-Error }
Write "Error: $file.name: $_" >>D:\\Backups\logfile.txt
}
continue;
} else {
foreach ($DB in $DB_Array) {
$backup_path_temp = $backup_path + $DB + '_' + $(Get-Date -f yyyy-MM-dd) + '.backup'
cmd /c "$path -w -h localhost -U postgres -Z3 -Fd -j 12 -f $backup_path_temp $DB"
}
}
# Delete files older than the $limit.
Get-ChildItem -Path $backup_path -Force |
Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } |
Remove-Item -Force -Recurse
答案 0 :(得分:0)
使用$LastExitcode
自动变量获取PowerShell中可执行文件的退出代码。