Powershell 使用Invoke-SQLCmd和-ErrorAction-SilentlyContinue尝试捕获

Powershell 使用Invoke-SQLCmd和-ErrorAction-SilentlyContinue尝试捕获,powershell,Powershell,基本上,我希望能够捕获从invokesqlcmd返回的警告,而不必停止脚本的运行。以下代码不起作用: TRY { Invoke-SQLCMD -Query "selects * from syscomments" -ServerInstance $ServerAddress -Database $DatabaseName -ErrorAction 'SilentlyContinue' } CATCH { Write-Host "[!] Errors returned, chec

基本上,我希望能够捕获从invokesqlcmd返回的警告,而不必停止脚本的运行。以下代码不起作用:

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