基本上,我希望能够捕获从 Invoke-SqlCmd 返回的警告,而不必停止脚本运行。以下代码不起作用:
TRY {
Invoke-SQLCMD -Query "selects * from syscomments" -ServerInstance $ServerAddress -Database $DatabaseName -ErrorAction 'SilentlyContinue'
}
CATCH {
Write-Host "[!] Errors returned, check log file for details" -ForegroundColor RED
$_ | Out-File -Append "path to log"
}
这只会抑制所有输出并且不会捕获错误。将错误类型更改为 Stop 确实会捕获错误,但我需要这些脚本在发生错误后继续运行。
最佳答案
您可以使用 trap
语句:
trap { # invoked on terminating errors
Write-Host "[!] Errors returned, check log file for details" -ForegroundColor RED
$_ | Out-File -Append "path to log"
continue # continue execution
}
# Elevate all non-terminating errors to (script-)terminating errors.
$ErrorActionPreference = 'Stop'
# All errors - whether non-terminating or terminating - now trigger
# the trap, which, due to use of `continue`, continues execution after each error.
Invoke-SQLCMD -Query "selects * from syscomments" -ServerInstance $ServerAddress -Database $DatabaseName
关于powershell - 尝试使用 Invoke-SQLCmd 和 -ErrorAction SilentlyContinue Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52157997/