Today’s post (and this blog's inaugural post!) is An Introduction to Error Handling in PowerShell. We will discuss error types, the $error variable, error action preferences, try/catch blocks, and $lastexitcode.
The first requirement is to understand the types of errors that can occur during execution.
Terminating vs. Non-Terminating Errors:
- Terminating Error: A serious error during execution that halts the command (or script execution) completely. Examples can include non-existent cmdlets, syntax errors that would prevent a cmdlet from running, or other fatal errors.
- Non-Terminating Error: A non-serious error that allows execution to continue despite the failure. Examples include operational errors such file not found, permissions problems, etc.
Update 12/13/2013: Writing a cmdlet? For further information regarding how a cmdlet should determine when to throw a terminating error or non-terminating error, MSDN has a nice explanation here.
Update 12/13/2013: Want to know if an error you encountered is terminating or non-terminating? Check to see if the error behavior is affected by changing the $ErrorActionPreference. According to the MSDN documentation here, "Neither $ErrorActionPreference nor the ErrorAction common parameter affect how Windows PowerShell responds to terminating errors (those that stop cmdlet processing).".
The $error variable:
When either type of error occurs during execution, it is logged to a global variable called $error. This variable is a collection of PowerShell Error Objects with the most recent error at index 0. On a freshly initialized PowerShell instance (no errors have occurred yet) the $error variable is ready and waiting as an empty collection:
In the next snippet I have executed a cmdlet that doesn’t exist, throwing an error. If we grab the count on $error, you will notice it has increased to one item. Dumping that object to the pipeline by accessing $error just prints the error we already saw, right back at us.
There is more available to us than just what is immediately visible. The ErrorRecord is a rich object that contains many useful properties to explore. Try piping the error to get-member (aliased by gm) to see what options we have available to us:
For details on what each property member provides, visit the ErrorRecord MSDN documentation. A couple important highlights:
- $error.InvocationInfo provides details about the context which the command was executed, if available.
- $error.Exception contains the original exception object as it was thrown to PowerShell. If we explore that object (also piped to get-member) we can see important items to pull up like stack trace, source, HResult, InnerException, etc.
Diving into the exception object itself ($error.Exception) can provide very important diagnostic details not immediately visible on the top level error record. This is especially useful in troubleshooting third party cmdlets!
Error Action Preference:
PowerShell halts execution on terminating errors, as mentioned before. For non-terminating errors we have the option to tell PowerShell how to handle these situations. This is where the error action preference comes in. Error Action Preference allows us to specify the desired behavior for a non-terminating error; it can be scoped at the command level or all the way up to the script level.
Available choices for error action preference:
- SilentlyContinue – error messages are suppressed and execution continues.
- Stop – forces execution to stop, behaving like a terminating error.
- Continue - the default option. Errors will display and execution will continue.
- Inquire – prompt the user for input to see if we should proceed.
- Ignore – (new in v3) – the error is ignored and not logged to the error stream. Has very restricted usage scenarios.
Example: Set the preference at the script scope to Stop, place the following near the top of the script file:
Example: Set the preference at the cmdlet level to Inquire, add error action switch (or alias EA):
The Try, Catch, and Finally statements allow us to control script flow when we encounter errors. The statements behave similar to the statements of the same name found in C# and other languages.
The behavior of try/catch is to catch terminating errors (exceptions). This means Non-terminating (operational) errors inside a try block will not trigger a Catch*. If you would like to catch all possible errors (terminating and non-terminating) – then simply set the error action preference to Stop. Remember that Stop error action forces a non-terminating error to behave like a terminating error, which means it can then be trapped in a catch block. Here is an example:
*Update 12/13/2013: In almost all cases, non-terminating errors will not trigger a catch. However I did recently observe a situation where a non-terminating error did trigger a catch block. It wasn't from a cmdlet, but an exception generated from directly calling a method on a .net object. So keep in mind that behavior might be possible.
You can also have Catch blocks that will only trap specific exceptions. The reason for doing this is so you can add different handlers for each possible failure condition that you may encounter. Some exceptions you may just want to log and exit, but others you may have a recovery action for. Here is a Catch statement that would trap a specific Exception type. The Exception type is displayed in brackets after the catch statement:
You might be wondering how I found the type name for the previous exception. The possible exceptions for cmdlets are not usually documented, so you may need to find them on your own. When an exception occurs you can look up the error in the $error collection, or while inside a catch block under the $_ variable. Call the GetType() method on the base exception to extract the FullName property. Like shown here:
Handling Errors from non-PowerShell processes:
What happens when your script needs to run an external process from PowerShell and you want to know if it succeeded? An example would be a cmdline tool such as robocopy.exe. It’s an external application that returns an exit code upon completion. But since it is an external process, its errors will not be caught in your try/catch blocks.
To trap this exit code utilize the $LastExitCode PowerShell variable.
When the launched process exits, PowerShell will write the exit code directly to $LastExitCode. In most cases an exit code of 0 means success, and 1 or greater indicates a failure. Check the external tool's documentation to verify of course.
Here it is seen in action: