尝试使用Invoke-SQLCmd和-ErrorAction静默继续捕获

时间:2018-09-04 02:24:45

标签: powershell

基本上,我希望能够捕获从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"
}

这只会抑制所有输出,而不会捕获错误。将错误类型更改为停止确实可以捕获该错误,但是我需要这些脚本才能在遇到错误后继续运行。

1 个答案:

答案 0 :(得分:1)

您可以使用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