Microsoft – PowerShell – Error Handling
Still struggling along with PowerShell and wishing someone will say “Walk a little Straighter” (http://www.youtube.com/watch?v=U1no7Or9BeI) to me.
But, from reading through others lens, here is my current understanding.
At a higher level, for instance at a module level, one gets to choose how errors are handled.
To do so, one needs to set the system variable $ErrorActionPreference.
The various available options for $ErrorActionPreference:
a) SilentlyContinue – Errors are not displayed and Script Continues Execution without visually acknowledging an error has occurred
b) Continue – Errors are displayed and Script continues execution
c) Stop – Errors are displayed and the Script is terminated
d) Inquire – Errors are displayed and user is prompted\asked how he \ she will like to proceed
To establish your choice, use something resembling:
$ErrorActionPreference = "SilentlyContinue"
Note that PowerShell also supports statement level “Error Reporting”.
My first initiation into this construct was from Steve Murawski’s Blog Entry.
Soccer is called the “Beautiful Game” and some words are best left hanging alone:
Deep Dive Error Handling:
If you hit a terminating error, your script, function, or command will stop. The error will be logged to the $error variable and written to the error stream. The $? will be set to false. You can use the trap construct (or the try/catch/finally construct in V2) to deal with terminating errors and we’ll cover that further in the fourth post in this series.
If you hit a non-terminating error, the result will depend on the $ErrorActionPreference in the scope or the –ErrorAction parameter. If the $ErrorActionPreference or –ErrorAction parameter is set to ‘Continue’, the error will be written to the error stream, added to the $error array, and the $? will be set to $false. ‘SilentlyContinue’ will not write an error to the Error stream, but $error and $? are updated. Finally, ‘Inquire’ provides you an option at each error as to whether to treat it as terminating or non-terminating. If treated as a non-terminating error, the error will be treated like the $ErrorActionPreference or –ErrorAction parameter is ‘Continue’.
From what I can surmise:
When an error is encountered, the following things happen:
- The System Array variable ($error) is updated; in this case a new entry is added to it
- A System Boolean variable ($?) is updated with the system keyword $false
- And, depending on the global variable $ErrorActionPreference or the statement level argument -ErrorAction, the error will be displayed or “eating up”
- At the statement level, errors can also be saved by using the “ErrorVariable” parameter
- Use PowerShell – Error Handling (Deep Dive) http://blog.usepowershell.com/category/deep-dive/error-handling/
- Hey, Scripting Guy! How Can I Use $ErrorActionPreference to Control Cmdlet Handling of Errors?
- Write Warning