Updates...
Update 12/29/2009: In addition to the below, you have several options in handling or trapping errors in powershell.
- cmdlet options
- ubiguitous parameters are avilible to all cmdlets by default. Some you may already know are ErrorAction and the ErrorVariable Parameters, both of which are used to handle nonterminating errors.
- command example: get-eventlog ..... -ErrorVariable Err -ErrorAction SilentlyContinue
- error option #1 for ErrorAction: Continue, print error and continue
- error option #2 for ErrorAction: Inquire, prompt user if they would like to continue, suspend or stop
- error option #3 for ErrorAction: Stop, Halt command execution or script
- trapping errors
- powershells default behavior is to display the error and then stop a command and/or fail on next action
- if you would like to use any type of custom error handling for an error, all you have to do is define an exception trap handler to prevent the terminating error from being sent.
- to define a trap use the following:
- trap ExceptionType {code; keyword} < exceptiontype specifies the type of error to trap (or accept) and if no exceptiontype is defined - the trap will accept all errors. code (optional) can consist of a command or a set of commands to run after a error is thrown. keyword will allow you to determine wheter the trap allows the statement block to terminate or execute.
- Trap error example:
- $sampleURL = " www.cibengineeringBunk.com"
trap [System. Management.Automation. MethodInvocationException] {
write-host ("ERROR: " + $_) - Foregroundcolor Red; Continue}
write-host " Getting IP address for" $sampleURL
write-host ( [System. Net.Dns] :: GetHostAddresses( "www. cibengineeringBunk . com") )
write-host " Work complete!.!"
- Trap error example
- write-host " Changing drive to i: "
trap {write- host("[ ERROR] " + $_) - Foregroundcolor Red; Continue}
get-item i: -ErrorAction Stop
$TXTFiles = get-childitem *. txt - ErrorAction Stop
write-host " finished with item retrieval"
On the topic of Error Handling:
VBScript's On Error Resume Next statement, and the corresponding On Error Goto 0 statement, are used to implement error handling. Essentially, you execute On Error Resume Next before any operation that may result in an error, and then check the special Err object to see if an error did indeed occur. VBScript's error handling is actually quite primitive, while PowerShell's is much more advanced.
In brief, you declare a trap, which is what PowerShell executes when an error (or exception) occurs (or is thrown). You do whatever you need to do within the trap, and then tell PowerShell to either continue, which resumes execution on the line following whatever line caused the exception, or break, which halts execution. For example: