-Powershell中的脚本块错误不在catch块中

时间:2018-10-11 11:01:48

标签: c# powershell

在我连接到服务器并使用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块。

1 个答案:

答案 0 :(得分:0)

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

  

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

Source