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.
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' {...}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With