Tuesday, January 27, 2009

PowerShell Code Repository - Get-Exception

I’ve been working with PowerShell’s error handling – trying to get a better handle on it. Yesterday, I looked at general error handling and discussed how to trap or catch an exception. By handling errors in your scripts, you make the script more production ready. And for many, this is a great thing!

One of the problems in trapping or catching an error is knowing what to look for. You can do a blanket catch, such as:

  1. try { 
  2. ... some dodgy bit of code...  
  3. catch { 
  4.  "code broke..." 
  5. }

At one level this works. You can catch an error and avoid your script dying – and maybe returning some interesting info. But there’s often a need to do a better job in detecting different exceptions and handling them differently. As I noted yesterday, a simple script could result in a number of discreet different errors each of which might mean different actions in your script. Along these lines (with PowerShell V2 of course):

  1. try { 
  2.   ... some dodgy bit of code...  
  3. catch [... exception 1]{ 
  4.   "code broke due to exception 1..." 
  5. catch [... exception 2]{ 
  6.   "code broke due to exception 2..." 
  7. catch {
  8.     “no idea why your code broke…”
  9. } 

In this second example, you are explicitly testing for two specific exceptions as well as a more general one. The idea here is that for the first two exceptions, you might be able to find some specific information to help the caller (or you) work out what went wrong and deal with it.

The big problem is knowing what exceptions you can trap. I saw a cool script today online - PowerShell Code Repository - Get-Exception. This script looks at all the loaded assemblies and works out what possible exceptions exist and then outputs them. Makes interesting reading and is a great reference.

Technorati Tags: ,

1 comment:

rupali thakur said...

MOF Repository - Enterprise Architecture Manager is a robust repository that organizes, integrates and analyzes information about an organization's architecture elements.