Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My PowerShell exceptions aren't being caught

Powershell v2:

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

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

Output:

output

and yet $error[0] | fl * -Force outputs System.IO.IOException: Not Enough permission to perform operation.

Problem: I don't see why I'm not catching this exception with my first catch block, since this matches the exception type.

like image 416
northben Avatar asked Dec 20 '25 09:12

northben


1 Answers

When you use the Stop action PowerShell changes the type of the exception to:

[System.Management.Automation.ActionPreferenceStopException]

So this is the what you should catch. You can also leave it out and catch all types. Give this a try if you want to opearte on different excdeptions:

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

    if($e -eq 'ItemNotFoundException' {...}
    if($e -eq 'IOException' {...}
}
like image 200
Shay Levy Avatar answered Dec 23 '25 07:12

Shay Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!