且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PowerShell捕获类型异常

更新时间:2023-11-11 12:26:40

将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 ...
}