Geeks With Blogs
Points To Share Mostly SharePoint

PowerShell Try Catch Finally

I am a relative novice to PowerShell and tried (pun intended) to use the “Try Catch Finally” in my scripts. Alas the structure that we love and use in C# (or even – shudder of shudders - in VB) does not always work in PowerShell. It turns out that it works only when the error is a terminating error (whatever that means).

Well, you can turn all your errors to the terminating kind by simply setting -

$ErrorActionPreference = "Stop", And later resetting it back to “Continue”, which is its normal setting.

Now, the lazy approach is to start all your scripts with:

$ErrorActionPreference = "Stop"

And ending all of them with:

$ErrorActionPreference = "Continue"

But this opens you to trouble because should your script have an error that you neglected to catch (it even happens to me!), your session will now have all its errors as “terminating”. Obviously this is not a good thing, so instead let’s put these two setups in the beginning of each Try block and in the Finally block as seen below:


That’s All Folks!!

Posted on Friday, June 1, 2012 9:25 PM | Back to top

Comments on this post: PowerShell Try Catch Finally

# re: PowerShell Try Catch Finally
Requesting Gravatar...
Thanks for the article, saved my time
Left by Saravan on Sep 18, 2012 7:38 AM

Your comment:
 (will show your gravatar)

Copyright © PointsToShare | Powered by: