首页 > 解决方案 > -Powershell中的脚本块错误不在catch块中

问题描述

我有一种情况,我正在连接到服务器并使用 powershell 执行操作,如果出现错误,那么它应该转到我正在执行其他操作的 catch 块。

 try{
 $Result = Invoke-Command -ComputerName "cmpname" -scriptblock {DTExec.exe /File "Z:\aaaaaaaSSIS\zzzzProjects\Z_Test\Integration test\test.dtsx"}  -ErrorAction Stop -credential $creds 
}

catch {
    "****An error occurred reading $file
}

现在在上述情况下,如果 -scriptblock 出现错误,则不会进入 catch 块。好像有问题,Invoke-Command -ComputerName然后它会进入 catch 块。

因此,当执行该行时,特别是 -script 块的任何地方发生错误时,我需要脚本进入 catch 块。

标签: c#powershell

解决方案


也许您没有将错误视为终止。尝试这个:

将所有错误视为终止:也可以使用 ErrorActionPreference 变量将所有错误视为终止。您可以为正在使用的脚本或整个 PowerShell 会话执行此操作。要在脚本中设置它,使第一行 $ErrorActionPreference = Stop。要为会话设置它,请在 PowerShell 控制台中键入 $ErrorActionPreference = Stop。

资源


推荐阅读