3

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.

2 Answers 2

8

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' {...}
}
Sign up to request clarification or add additional context in comments.

5 Comments

ahh ok, that makes sense about the errorpreference. So then what's the deal with the catch [exceptiontype] syntax? According to blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/…, that's the way to do it...
Thats how you deal with terminating exceptions. Your was a non-terminating(which is why you specified erroraction to stop). That's why u have to use shay's solution.
Exactly. By the way, if you look at the article you'll see that the catch for [System.Management.Automation.PSArgumentException] is not printing, only other values, such as for [system.exception] (which in my opinion is not necessary since all exceptions are of that type.
ok, that helps a lot. I'm going to use -erroraction Stop with try/catch blocks for each individual command/function that I am concerned about.
0

I like the Trap method for global error handling, as I wanted to stop my scripts if unhandled exceptions were occurring to avoid corrupting my data. I set ErrorActionPreference to stop across the board. I then use Try/Catch in places where I may expect to see errors in order to stop them halting the scripts. See my question here Send an email if a PowerShell script gets any errors at all and terminate the script

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.