【发布时间】:2011-12-05 05:08:51
【问题描述】:
我遇到了 PowerShell 的问题,即使在 catch 命令中明确提及异常,它也不会捕获异常。
在这种情况下,我试图确定 ProcessID 是否仍在运行,如果没有,它将采取一些措施。
我正在努力的示例代码块是:
try {
Get-Process -Id 123123 -ErrorAction 'Stop'
}
catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
"Caught by Exception Type: Process is missing"
}
catch {
if ($_.Exception.getType().FullName -eq "Microsoft.PowerShell.Commands.ProcessCommandException") {
"Caught by Catch All: Process is missing"
}
}
执行此代码块时,输出为:
Caught by Catch All: Process is missing
您会期望触发第一个 catch 条件,因为它命名了正确抛出的异常,但它没有触发。
更糟糕的是,当第二个 catch 命令运行(它捕获任何东西)时,它会查询异常类型的名称并检查它是否是“Microsoft.PowerShell.Commands.ProcessCommandException”(它是),然后采取适当的步骤。
我知道我可以解决这个问题,但我觉得我缺少关于 PowerShell 如何处理异常的基本方法。
谁能帮我解释一下?
【问题讨论】:
标签: exception powershell