Reader small image

You're reading from  Mastering PowerShell Scripting - Fourth Edition

Product typeBook
Published inJun 2021
PublisherPackt
ISBN-139781800206540
Edition4th Edition
Right arrow
Author (1)
Chris Dent
Chris Dent
author image
Chris Dent

Chris Dent is an automation specialist with deep expertise in the PowerShell language. Chris is often found answering questions about PowerShell in both the UK and virtual PowerShell user groups. Chris has been developing in PowerShell since 2007 and has released several modules over the years.
Read more about Chris Dent

Right arrow

Error Handling

Errors communicate unexpected conditions and exceptional circumstances. Errors often contain useful information that you can use to diagnose a condition.

PowerShell has two different types of errors, terminating and non-terminating, and several different ways to raise and handle them.

Error handling in PowerShell is a complex topic, which is not helped by incorrect assertions in help documentation surrounding terminating errors. These challenges are explored in this chapter.

Self-contained blocks of code are described as scripts in this chapter. That is, functions, script blocks, and scripts can be considered interchangeable in the context of error handling.

This chapter covers the following topics:

  • Error types
  • Error actions
  • Raising errors
  • Catching errors

Error types

As mentioned above, PowerShell defines two different types of errors: terminating and non-terminating errors.

Each command in PowerShell may choose to raise either of these, depending on the operation.

Non-terminating errors

A non-terminating error, a type of informational output, is written without stopping a script. Non-terminating errors exist to allow a command to continue in the event of a partial failure. For example, if a command is acting on a pipeline and one item fails, the command can write an error and continue to process the remaining items.

Non-terminating errors can be written using the Write-Error command, although a deeper analysis of this approach and alternatives are explored later in this chapter.

The following example demonstrates how a non-terminating error can be used in a function accepting pipeline input:

function Update-Value {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        ...

Error actions

The -ErrorAction parameter and the ErrorActionPreference variable are used to control what happens when a non-terminating error is encountered, subject to the previous notes about throw.

The -ErrorAction parameter is made available on a command when the CmdletBinding attribute is present. The CmdletBinding attribute is implicitly added if one or more parameters in a script use the Parameter attribute.

By default, -ErrorAction is set to Continue. Non-terminating errors will be displayed, but a script will continue to run.

$ErrorActionPreference is a scoped variable, which you can use to affect all commands in a particular scope and any child scopes. By default, $ErrorActionPreference is set to Continue. You can override the variable in child scopes (such as a function inside a script).

All errors in a session are implicitly added to the reserved variable $Error unless the error action is set to Ignore. Now, $Error is an ArrayList and contains...

Raising errors

When writing a script, it may be desirable to use errors to notify the person running the script of a problem. The severity of the problem will dictate whether an error is non-terminating or terminating.

If a script makes a single change to many diverse, unrelated objects, a terminating error might be frustrating for anyone using the script.

On the other hand, if a script fails to read a critical configuration file, a terminating error is likely the right choice.

Error records

When an error is raised in PowerShell, an ErrorRecord object is created (explicitly or implicitly).

An ErrorRecord object contains several fields that are useful for diagnosing an error. ErrorRecord can be explored using Get-Member or by using the Get-Error command.

For example, an ErrorRecord will be generated when attempting to divide by 0:

100 / 0 
$record = $Error[0] 

The ErrorRecord object that was generated includes ScriptStackTrace, which includes the script...

Catching errors

Capturing an error so that a script can react to that error depends on the error type.

  • Non-terminating errors can be captured by using ErrorVariable
  • Terminating errors can be captured using either a try, catch, and finally statement, or by using a trap statement

The -ErrorVariable parameter can be used to create a scoped alternative to the $Error variable.

ErrorVariable

The $Error variable is a collection (ArrayList) of handled and unhandled errors raised in the PowerShell session.

You can use the -ErrorVariable parameter to name a variable that should be used for a specific script. The ErrorVariable accepts the name of a variable and is created as an ArrayList.

The following function writes a single error using the Write-Error command:

function Invoke-Something { 
    [CmdletBinding()] 
    param ( ) 
 
    Write-Error 'Invoke-Something Failed' 
}

The command can be run using the -ErrorVariable parameter...

Summary

Error handling in PowerShell is a complex topic, perhaps made more so by inconsistencies in the documentation that can trip up new and experienced PowerShell users.

PowerShell includes the concept of non-terminating errors. Non-terminating errors allow a script, such as one acting on a pipeline, to carry on in the event of an error.

Error handling cannot be said to be consistently implemented in PowerShell. It is not always true that a problem that prevents an action from continuing will be described as a terminating error. The reverse is also true: not all actions that allow an action to continue are described as non-terminating errors. Great care must therefore be taken when writing code to correctly handle error conditions.

Non-terminating errors should be used when writing commands that expect to act on more than one object if the error is restricted to that one object and does not prevent a broader activity from completing.

You use terminating...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering PowerShell Scripting - Fourth Edition
Published in: Jun 2021Publisher: PacktISBN-13: 9781800206540
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Chris Dent

Chris Dent is an automation specialist with deep expertise in the PowerShell language. Chris is often found answering questions about PowerShell in both the UK and virtual PowerShell user groups. Chris has been developing in PowerShell since 2007 and has released several modules over the years.
Read more about Chris Dent