0
0
PowerShellscripting~5 mins

$Error automatic variable in PowerShell

Choose your learning style9 modes available
Introduction

The $Error variable helps you see what errors happened in your PowerShell session. It keeps a list of recent errors so you can check and fix problems.

You want to find out why a command did not work.
You need to log errors from a script to understand issues later.
You want to show error details to help someone else fix a problem.
You want to clear old errors before running new commands.
You want to handle errors differently based on what happened.
Syntax
PowerShell
$Error

$Error is an automatic variable that stores error objects in a list.

The newest error is at $Error[0], and older errors have higher indexes.

Examples
Shows the most recent error message.
PowerShell
Write-Output $Error[0]
Clears all errors from the $Error list.
PowerShell
$Error.Clear()
Runs a command that causes an error, then shows the error details.
PowerShell
try { Get-Item 'C:\no_such_file.txt' } catch { Write-Output $Error[0] }
Sample Program

This script tries to get a file that does not exist. When it fails, it prints a message and shows the error details from $Error[0]. Then it shows how many errors are stored in $Error.

PowerShell
try {
    Get-Item 'C:\no_such_file.txt'
} catch {
    Write-Output "An error happened."
    Write-Output "Error details:"
    Write-Output $Error[0]
}

Write-Output "Total errors stored: $($Error.Count)"
OutputSuccess
Important Notes

$Error keeps errors only for the current session or script run.

You can use $ErrorActionPreference to control how PowerShell reacts to errors.

Summary

$Error stores recent errors automatically.

The newest error is $Error[0].

You can clear errors with $Error.Clear().