Welcome to VSTSC's Community Server | | Help

trap [exception] { #insert code here} .... -ea stop

First off I'm not The PowerShellGuy (if you want tons of powershell information go there first)...I'm just getting started with PowerShell but I can already see how it can be extremely useful to a database developer and database administrator.  I plan on posting on PowerShell from time to time in this blog when I find something particularly useful to either of the previously mentioned rolls but for now I'm going to go over the TRAP object in PowerShell more to the point of what I have learned on how to use it.  The trap object is pretty straight forward and is similar to a onError event.  The main thing I want to explain in this post is that any cmdlet that you want to trap an error needs its ErrorAction or -ea property set to stop.  That’s it, that short, that sweat, but I had a hard time finding anything on the web or in three different PS books (Not mentioned to protect the guilty) on how to properly execute a trap.  Below I give a simple example:


$NoSuchDirectory="c:\noSuchDirectory"

#nothing happens as expected....script continues
function noTrap
{
 get-childItem $NoSuchDirectory=
}
noTrap


#nothing happens as expected(?)....script continues
function withTrap
{
 trap {
  #insert trap info here
  "Trapped Error! kind of"
 }
 get-childItem $NoSuchDirectory=
}
withTrap

#error is trapped....script stops then continues
function withTrap_2
{
 trap {
  #insert trap info here
  "Trapped Error! kind of"
  continue;
 }
 get-childItem $NoSuchDirectory= -ea stop

 #notice I've chanaged the ErrorAction on GCI to STOP from
 #the default continue, this is what allows the script to
 #trap the error.  If you change it to continue the trap
 #never fires
}
withTrap_2
"After the Trap"

 

 Now I just need to figure out how to get the SQL 2008 powershell snapins to port over to a machine that doesn't have SQL 2008 installed on it.

Published Monday, April 14, 2008 6:33 PM by steve
Filed under:

Comments

Anonymous comments are disabled