#PSTip Ignoring errors

Note: This tip requires PowerShell 3.0 or above.

PowerShell lets you control how it responds to a non-terminating error (an error that does not stop the cmdlet processing) globally via the $ErrorActionPreference preference variable, or at a cmdlet level using the -ErrorAction parameter. Both ways support the following values:

Stop: Displays the error message and stops executing.
Inquire: Displays the error message and asks you whether you want to continue.
Continue: Displays the error message and continues (Default) executing.
SilentlyContinue: No effect. The error message is not displayed and execution continues without interruption.

No matter which value you choose, the error is written to the host and added to the $error variable. Starting with PowerShell 3.0, at a command level only (e.g ErrorAction), we have an additional value: Ignore. When Ignore is specified, the error is neither displayed not added to $error variable.

# check the error count
PS> $error.Count

# use SilentlyContinue to ignore the error
PS> Get-ChildItem NoSuchFile -ErrorAction SilentlyContinue

# error is ignored but is added to the $error variable
PS> $error.Count

PS> $error.Clear()

# Using Ignore truly discards the error and the error is not added to $error variable
PS> Get-ChildItem NoSuchFile -ErrorAction Ignore
PS> $error.Count

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts