我遇到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"
}
}
Run Code Online (Sandbox Code Playgroud)
执行此代码块时,输出为:
Caught by Catch All: Process is missing
Run Code Online (Sandbox Code Playgroud)
您可能希望触发第一个catch条件,因为它命名正确抛出的异常,但它不会触发.
更糟糕的是,当第二个catch命令运行(捕获任何东西)时,它会查询异常类型的名称并检查它是否是"Microsoft.PowerShell.Commands.ProcessCommandException"(它是),然后采取适当的步骤.
我知道我可以解决这个问题,但我觉得我缺少关于PowerShell如何处理异常的基本方法.
任何人都可以为我阐明这一点吗?