Saturday, November 22, 2008

Error Handling in PowerShell V2 (continued)

One of the many interesting features in PowerShell V2 is improved error handling. In particular, you’ll have the try/catch/finally syntax that C# programmers have had for eons. This is particularly useful when creating production scripts that need to do error handling. I discussed/demonstrated this feature in a recent blog entry.

The basic syntax of this new Powershell feature is as follows:

try { <something that may fail>} catch { <deal with the error>} finally { <any cleanup that needs to be done}

This is pretty straightforward: PowerShell first tries to do whatever is inside the first script block (i.e. something that may fail). If there’s an exception thrown, PowerShell executes the second script block (i.e. deal with the error). Finally, whether or not the dangerous thing threw and exception, or now, you perform the last script block (i.e. any cleanup that needs to be done).

Using the sample posted in my scripts blog, here’s one bit of code:

Try {$i=1} Catch {"Caught a problem in try 1"} Finally {"All done with 1st try"}

As to be expected, this script produces a single line of output: “All done with 1st try”)!

With PowerShell V2, you’ll need to specify the try and catch blocks (well in order to actually catch an error). In this case, we try a simple assignment (that really should work!). If there was an error executing that, the catch block would print the message. And finally, no matter what just happened, PowerShell prints the final message.

If you are writing code that expects different sorts of errors, you can add several catch blocks to specify different error handing depending on the error encountered. You can also pick up details of the error by using the $Error built-in variable. $Error is, in effect, an array of all the errors you’ve had in the current session. To find out which one was the last, you can use $error[$error.count-1] to get the last error.

 

No comments: