Brian - Day 22


This chapter was interesting, since I've never even considered trying to handling errors in a script (or fuction, or module, or advanced scripting function).  My version of error handling was manually correct with the error if the script produced an error.  The cool thing with PowerShell, and a little preemptive thinking, we can make the script do some of that work for us.


PowerShell has a default behavior for error handling, which is set to Continue.  This means that, by default, when PowerShell runs into an error it continues processing the rest of the work.  This is what's called a non-terminating problem, which means we can't really do anything with it (as far as error trapping/handling).  There are four different actions for to be taken to handle errors, but the only on we're really concerned with is Stop.  If the error action is set to Stop we can actually trap the error and doing something with it.


There are two ways in PowerShell to trap and handle errors.  The first one is the Trap{} construct.  The tricky thing with a Trap{} construct is designed as a catch all for error handling.  Doing this brings back the concept of scopes, which traps are very sensitive to.  The main takeaway is that it's not really the best way to handle errors, but could be used to catch what's left of the script (unexpected errors).  


The way to think about error handling is that we're trying to trap and handle errors that we are anticipating.  If we know that a command could fail for a somewhat likely reason (file not found is a good example), then we can plan for that.  The Try{} construct is a very good way to accomplish this.  The Try{} construct is different from the Trap{} construct because it can trap and handle errors on a per-command basis.  This enables us to handle different errors we're expecting in different ways.  For instance, if we know that a computer may or may not be reachable we can tell PowerShell to log the computer name to a file and keep going.  If a file we need doesn't exist, then we can halt the script completely.  We use the Try{} construct to trap the error, and immediately follow it with a Catch{} construct to handle it.  The logic is simple:  try this command, if it doesn't work do this.  


Another thing we can do is use an error variable.  Sometimes outputting a computer name that couldn't be contacted would be sufficient, but other times we could use more information on the error for troubleshooting purposes.  The -ErrorVariable parameter is part of the common parameters that's available for every PowerShell cmdlet.  Using this we can capture more informative errors into another file, in case we would need it.  



Posted Mar 24 2012, 04:26 PM by Don Jones
Copyright 2012 All rights reserved.