PowerShell Error Variable
The error variable is a list that collects errors from commands. You can count its entries, capture one error into your own variable, and clear the list.
Count errors before and after
Count the list before a failing command, then count it again. One error adds one entry.
"Before: " + $Error.Count
Get-Item "/definitely-not-here-xyz" -ErrorAction SilentlyContinue
"After: " + $Error.CountCapture into your own variable
The -ErrorVariable flag saves the error under a name you choose. The script does not stop.
Get-Item "/definitely-not-here-xyz" -ErrorVariable myError -ErrorAction SilentlyContinue
"Captured: " + $myError.Count
"Message: " + $myError[0].Exception.MessageClear the list
Clear empties the list. Count it again to prove it is empty.
Get-Item "/definitely-not-here-xyz" -ErrorAction SilentlyContinue
"Before clear: " + $Error.Count
$Error.Clear()
"After clear: " + $Error.CountExample
"Before: " + $Error.Count
Get-Item "/definitely-not-here-xyz" -ErrorVariable myError -ErrorAction SilentlyContinue
"Captured: " + $myError.Count
"Total: " + $Error.Count
$Error.Clear()
"After clear: " + $Error.CountKey points
- $Error: the list that collects every error in the current session.
- Count: the number of entries in the list, read as $Error.Count.
- -ErrorVariable: a flag that captures a command error into a variable you name.
- Captured error: the same error record, saved under your own variable name.
- Clearing: emptying the list with $Error.Clear().
In this example, the list starts empty, one failing command is captured into myError, both counts read 1, and clearing the list brings its count back to 0.
Note
Capturing an error does not keep it out of the main list.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which flag captures a command error into a variable you name?