Home > Articles > Home & Office Computing > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Understanding Errors

PowerShell errors are divided into two types: terminating and nonterminating. Terminating errors, as the name implies, stop a command. Nonterminating errors are generally just reported without stopping a command. Both types of errors are reported in the $Error variable, which is a collection of errors that have occurred during the current PowerShell session. This collection contains the most recent error, as indicated by $Error[0] up to $MaximumErrorCount, which defaults to 256.

Errors in the $Error variable can be represented by the ErrorRecord object. It contains error exception information as well as a number of other properties that are useful for understanding why an error occurred

The next example shows the information that is contained in InvocationInfo property of an ErrorRecord object:

PS C:\> $Error[0].InvocationInfo


MyCommand        : Get-ChildItem
ScriptLineNumber : 1
OffsetInLine     : -2147483648
ScriptName       :
Line             : dir z:
PositionMessage  :
                   At line:1 char:4
                   + dir  <<<< z:
InvocationName   : dir
PipelineLength   : 1
PipelinePosition : 1



PS C:\>

Based on this information, you can determine a number of details about $Error[0], including the command that caused the error to be thrown. This information is crucial to understanding errors and handling them effectively.

Use the following command to see a full list of ErrorRecord properties:

PS C:\> $Error[0] | get-member -MemberType Property


   TypeName: System.Management.Automation.ErrorRecord

Name                  MemberType Definition
----                  ---------- ----------
CategoryInfo          Property   System.Management.Automation.ErrorCategoryI...
ErrorDetails          Property   System.Management.Automation.ErrorDetails E...
Exception             Property   System.Exception Exception {get;}
FullyQualifiedErrorId Property   System.String FullyQualifiedErrorId {get;}
InvocationInfo        Property   System.Management.Automation.InvocationInfo...
TargetObject          Property   System.Object TargetObject {get;}



PS C:\>

Table 3.1 shows the definitions for each of the ErrorRecord properties that are listed in the preceding example:

Table 3.1. ErrorRecord Property Definitions

Property

Definition

CategoryInfo

Indicates under which category an error is classified

ErrorDetails

Can be null, but when used provides additional information about the error

Exception

The error that occurred

FullyQualifiedErrorId

Identifies an error condition more specifically

InvocationInfo

Can be null, but when used explains the context in which the error occurred

TargetObject

Can be null, but when used indicates the object being operated on

  • + Share This
  • 🔖 Save To Your Account