0
0
PowerShellscripting~10 mins

$Error automatic variable in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $Error automatic variable
Run Command
Error Occurs?
NoNo change to $Error
Yes
Add Error to $Error Array
Access $Error for Details
Use or Clear $Error
When a command runs, if an error happens, PowerShell adds it to the $Error list. You can check or clear this list anytime.
Execution Sample
PowerShell
$Error.Clear()
Get-Item nofile.txt
$Error[0]
This clears errors, tries to get a missing file (causing error), then shows the latest error.
Execution Table
StepCommand RunError Occurred?$Error CountActionOutput
1$Error.Clear()No0Clear all errorsNo output
2Get-Item nofile.txtYes1Add error to $ErrorError: Cannot find path 'nofile.txt' because it does not exist.
3$Error[0]N/A1Show latest errorError details about missing file
💡 No more commands, $Error holds 1 error from missing file
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
$Error.CountVaries (depends on session)011
$Error[0]Most recent errorNoneNew error from Get-ItemSame error shown
Key Moments - 3 Insights
Why does $Error keep growing with each error?
Because PowerShell adds each new error to the start of the $Error array, growing its size as shown in step 2 of the execution_table.
What does $Error.Clear() do?
It empties the $Error array, removing all previous errors, as seen in step 1 where $Error.Count becomes 0.
How do I see the most recent error?
Use $Error[0] to get the latest error, demonstrated in step 3 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $Error.Count after running Get-Item nofile.txt?
A0
B1
C2
DError
💡 Hint
Check the $Error Count column at step 2 in the execution_table.
At which step is the $Error array cleared?
AStep 3
BStep 2
CStep 1
DNever
💡 Hint
Look at the Command Run column and the Action at step 1.
If you run another failing command after step 2, how does $Error.Count change?
AIt increases by 1
BIt decreases
CIt stays the same
DIt resets to 0
💡 Hint
Recall that each error adds one item to $Error as shown in step 2.
Concept Snapshot
$Error is an automatic array holding recent errors.
New errors are added at the start.
Use $Error[0] for the latest error.
Clear errors with $Error.Clear().
It helps track what went wrong in commands.
Full Transcript
The $Error automatic variable in PowerShell keeps a list of recent errors from commands. When you run a command, if it fails, PowerShell adds that error to the start of the $Error array. You can see how many errors are stored by checking $Error.Count. To clear all errors, use $Error.Clear(). To see the most recent error, use $Error[0]. This helps you understand what problems happened during your script or session.