PowerShell Try Catch Finally

Posted by PointsToShare on Geeks with Blogs See other posts from Geeks with Blogs or by PointsToShare
Published on Fri, 01 Jun 2012 19:25:57 GMT Indexed on 2012/06/02 4:41 UTC
Read the original article Hit count: 557

Filed under:

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:

clip_image002

That’s All Folks!!

© Geeks with Blogs or respective owner