PowerShell捕获类型异常 [英] PowerShell catching typed exceptions

查看:224
本文介绍了PowerShell捕获类型异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在这种情况下,我在PowerShell中遇到问题,即使在catch命令中明确提到了异常,它也不会捕获异常。 '试图确定一个ProcessID是否仍在运行,如果没有,那么它将采取一些措施。



我正在努力的示例代码块是: p>

  try {
Get-Process -Id 123123 -ErrorAction'Stop'
}
catch [
$ {
if($ _。Exception.getType()。FullName

}

执行此代码块时,输出为:

 抓住所有:进程失踪

你会练习ct的第一个catch条件触发,因为它命名正确抛出的异常,但它不会触发。



为了使事情变得更糟,当第二个catch命令运行时它捕获任何东西),它查询异常类型的名称,并检查它是否为Microsoft.PowerShell.Commands.ProcessCommandException(它是),然后采取适当的步骤。



我知道我可以解决这个问题,但是我觉得我错过了一个关于PowerShell如何处理异常的基本方法。



任何人都可以看出这一点吗?

解决方案

将ErrorAction设置为Stop时,非终止错误将被包装并抛出为
System.Management。 Automation.ActionPreferenceStopException,这是你想要捕获的类型。

  try 
{
Get-Process -Id 123123 -ErrorAction Stop
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
...做某事...
}


I'm having an issue with PowerShell where it will not catch an exception even when the exception is explicitly mentioned in the catch command.

In this case, I'm trying to determine if a ProcessID is still running, and if not then it will take some actions.

The sample code block that I am struggling with is:

    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"
      }
    }

When this code block is executed the output is:

Caught by Catch All: Process is missing

You would expect the first catch condition to trigger as it names the exception being thrown correctly, but it doesn't trigger.

To make things worse, when the second catch command runs (which catches anything) it queries the name of the exception type and checks if it is "Microsoft.PowerShell.Commands.ProcessCommandException" (which it is) and then takes appropriate steps.

I know I can work around this, but I feel I'm missing a fundamental way about how PowerShell handles Exceptions.

Can anyone shed light on this for me?

解决方案

When you set ErrorAction to Stop, non-terminating errors are wrapped and thrown as type System.Management.Automation.ActionPreferenceStopException, this is the type you want to catch.

try 
{
    Get-Process -Id 123123 -ErrorAction Stop
} 
catch [System.Management.Automation.ActionPreferenceStopException]
{
    ... do something ...
}

这篇关于PowerShell捕获类型异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆