2
function Test($cmd)
{
          Try
         {
                  Invoke-Expression $cmd -ErrorAction Stop
         }
         Catch
         {
                  Write-Host "Inside catch"
         }

         Write-Host "Outside catch"
}

$cmd = "vgc-monitors.exe"  #Invalid EXE
Test $cmd

$cmd = "Get-Content `"C:\Users\Administrator\Desktop\PS\lib\11.txt`""
Test $cmd
#

第一次使用 $cmd = "vgc-monitors.exe" 调用 Test() (系统中不存在此 exe)

*成功捕获异常

*文字“内接”“外接”打印

#

$cmd = "Get-Content "C:\Users\Administrator\Desktop\PS\lib\11.txt""用(11.txt在指定路径中不存在)第二次调用Test( )

*未捕获异常

*文本“内部捕获”未打印“

* 得到以下错误信息

Get-Content : Cannot find path 'C:\Users\Administrator\Desktop\PS\lib\11.txt' because it does not exist.
At line:1 char:12
+ Get-Content <<<<  "C:\Users\Administrator\Desktop\PS\lib\11.txt"
    + CategoryInfo          : ObjectNotFound: (C:\Users\Admini...p\PS\lib\11.txt:String) [Get-Content], ItemNotFoundEx
   ception
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

问题:

我希望捕获第二个异常。我无法弄清楚我的代码中的错误。

谢谢

朱加里

4

1 回答 1

2

您正在申请-ErrorAction StopInvoke-Expression它执行得很好。要使错误操作指令适用于调用的表达式,您需要将其附加到$cmd

Invoke-Expression "$cmd -ErrorAction Stop"

或设置$ErrorActionPreference = "Stop"

$eap = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try {
  Invoke-Expression $cmd
} catch {
  Write-Host "Inside catch"
}
$ErrorActionPreference = $eap

后者是更稳健的方法,因为它不对$cmd.

于 2013-09-02T14:01:04.090 回答