Dealing with errors in PowerShell
When creating a script in any language, error handling is needed to ensure proper operations. Error handling is useful when debugging scripts and ensuring scripts work properly, but they can also present alternative methods of accomplishing tasks.
How to do it...
Carry out the following steps:
Create a simple function that uses no error handling
Function Multiply-Numbers { Param($FirstNum, $SecNum) Write-Host ($FirstNum * $SecNum) }
Test the function using various arguments:
Update the function using a
Try
/Catch
block:Function Multiply-Numbers { Param($FirstNum, $SecNum) Try { Write-Host ($FirstNum * $SecNum) } Catch { Write-Host "Error in function, present two numbers to multiply" } }
Test the
Multiply-Numbers
function using various arguments:In the PowerShell console, execute a command to generate an error such as
Get-Item foo
.View the
$Error
variable to return the error code history.
How it works...
In the first step, we create a function that takes two numbers, multiplies them, and returns the result. As we see in the second step, the function operates normally as long as two numbers are presented, but if something other than a number is presented, then an unfriendly error is returned.
In the third step, our updated script uses a Try/Catch block to find errors and return a more friendly error. The Try
block attempts to perform the multiplication, and if an error is returned then processing exits. When the Try
block fails for any reason, it then executes the Catch
block instead. In this case, we are returning a command specific error message, in other scenarios we could initiate an alternative task or command that was based on the error.
The fifth and sixth steps generate an error in the PowerShell console, and then show the $Error
variable. The $Error
variable is an in-built array that automatically captures and stores errors as they happen. You can view the variable to report all errors listed, or you can use indexing such as $Error[1]
to return specific errors.
There's more...
Clearing error codes: By default, the
$Error
array will retain a number of error codes. These errors are only removed from the array when it reaches its maximum size, or when the user session is ended. It is possible to clear out the array before doing a task, so that you can then review the$Error
array after and know that all the alerts are relevant.$Error.Count $Error.Clear() $Error.Count
This example starts by returning the number of items in the array. Then
$Error.Clear()
is called to empty the array. Lastly, the number of array items is returned to confirm that it has been cleared.$ErrorActionPreference
: In many programming/scripting languages, there are methods to change the default action when an error occurs. In VBScript, we had the option "On Error Resume Next", which told the script to continue on as though no error had occurred. In PowerShell, we have the$ErrorActionPreferece
variable. There are four settings for this variable:Stop: Whenever an error occurs, the script or process is stopped. This is the default action.
Continue: When an error occurs, the error will be reported and the process will continue.
SilentlyContinue: When an error occurs, PowerShell will attempt to suppress the error and the process will continue. Not all errors will be suppressed.
Inquire: When an error occurs, PowerShell will prompt the operator to take the correct action.
To set your preference, simply set the variable to the desired string value as shown in the following code:
$ErrorActionPreference = "Stop"