powershell - 尝试使用 Invoke-SQLCmd 和 -ErrorAction SilentlyContinue Catch

标签 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"
}

这只会抑制所有输出并且不会捕获错误。将错误类型更改为 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/

相关文章:

xml - 使用PowerShell,如何使用多个命名空间

powershell - 从哈希表数组的键创建数组

powershell - Powershell ConvertTo-json输出为小写

powershell - 无法运行 PowerShell 卸载脚本

c# - 使用 .NET(PowerShell 或 .NET)获取 BCD 条目

java - 指定Java中的默认文件编码

powershell - 代理身份验证问题: Azure Powershell Build Task on premise TFS server 2015

powershell - 如何使用 WMI 和 Powershell 保存对 Windows 组的更改

powershell - 停止循环的Powershell脚本并杀死由它启动的远程进程

powershell - VSTS 任务组 Powershell 参数