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 ors.exe”调用Test() (此exe在系统中不存在)
*异常捕获成功
*文本“内部捕捉”“外部捕捉”打印
使用$cmd = "Get-Content "C:\Users\Administrator\Desktop\PS\lib\11.txt""再次调用Test() (指定路径中不存在11.txt)
*未捕获异常
*文本"Inside catch“未打印”
*获取以下错误信息
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问题:
我希望捕获第二个异常。我找不出代码中的错误。
谢谢
Jugari
发布于 2013-09-02 22:01:04
您正在对Invoke-Expression应用-ErrorAction Stop,它可以很好地执行。要使错误操作指令应用于被调用的表达式,您需要将其附加到$cmd
Invoke-Expression "$cmd -ErrorAction Stop"或设置$ErrorActionPreference = "Stop"
$eap = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try {
Invoke-Expression $cmd
} catch {
Write-Host "Inside catch"
}
$ErrorActionPreference = $eap后者是更健壮的方法,因为它不会对$cmd做出假设。
https://stackoverflow.com/questions/18572949
复制相似问题