Professional Error Handling

by May 16, 2022

Often PowerShell scripts use a very simple form of error reporting that is structured like this:

# clearing global error list:
$error.Clear()
# hiding errors:
$ErrorActionPreference = 'SilentlyContinue'

# do stuff:
Stop-Service -Name Spooler
dir c:gibtsnichtabc


# check errors at end:
$error.Count 
$error | Out-GridView

While there is nothing wrong with this, you should understand that $error is a global variable, so if you use external code in your scripts (i.e. functions or modules written by someone else), these authors may have employed the same technique, and if they did and cleared the global error list, then you are losing errors that had been recorded before.

A much better and more solid way uses private variables for logging. There is actually not that much of a rewrite:

# hiding errors:
$ErrorActionPreference = 'SilentlyContinue'
# telling all cmdlets to use a private variable for error logging:
$PSDefaultParameterValues.Add('*:ErrorVariable', '+myErrors')
# initializing the variable:
$myErrors = $null

# do stuff:
Stop-Service -Name Spooler
dir c:gibtsnichtabc


# check errors at end USING PRIVATE VARIABLE:
$myErrors.Count
$myErrors | Out-GridView

The basic trick is to define a default parameter value for -ErrorVariable, and assign it the name of your private variable. Make sure you add a “+” before the name so new errors are appended and not overwriting existing errors.


Twitter This Tip! ReTweet this Tip!