My PowerShell exceptions are not getting hit

Powershell v2:

try { Remove-Item C:\hiberfil.sys -ErrorAction Stop }
catch [System.IO.IOException]
{ "problem" }
catch [System.Exception]
{ "other" }

      

I'm using the hibernate file as an example, of course. There is actually another file that I expect may not have permission to delete sometimes, and I want to catch this exception.

Output:

output

      

but $error[0] | fl * -Force

outputsSystem.IO.IOException: Not Enough permission to perform operation.

Problem: I don’t understand why I don’t catch this exception with my first catch block, since this is the type of exception.

+3


source to share


2 answers


When using the Stop action, PowerShell changes the exception type to:

[System.Management.Automation.ActionPreferenceStopException]

      



So this is what you have to catch. You can also leave it and catch all types. Try to try if you want to drop different exceptions:

try 
{
    Remove-Item C:\pagefile.sys -ErrorAction Stop
}
catch
{
    $e = $_.Exception.GetType().Name

    if($e -eq 'ItemNotFoundException' {...}
    if($e -eq 'IOException' {...}
}

      

+7


source


I like the Trap method for handling global errors as I wanted to stop my scripts if no exceptions were handled to avoid corrupting my data. I have set ErrorActionPreference to stop in all directions. Then I use Try / Catch in places where I can expect errors to appear to stop the scripts from stopping them. See my question here Send an email if the PowerShell script gets any errors at all and exits the script



0


source







All Articles