Bird
Raised Fist0
PowerShellscripting~10 mins

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

Choose your learning style10 modes available
Concept Flow - $Error automatic variable
Run Command
↓
Error Occurs?
No→No 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.

Practice

(1/5)
1. What does the PowerShell automatic variable $Error store?
easy
A. A list of recent errors encountered during the session
B. All successful command outputs
C. User input history
D. System environment variables

Solution

  1. Step 1: Understand the purpose of $Error

    $Error automatically collects errors that occur during the PowerShell session.
  2. Step 2: Differentiate from other variables

    It does not store outputs, inputs, or environment variables, only errors.
  3. Final Answer:

    A list of recent errors encountered during the session -> Option A
  4. Quick Check:

    $Error stores errors [OK]
Hint: Remember: $Error always holds recent errors [OK]
Common Mistakes:
  • Thinking $Error stores command outputs
  • Confusing $Error with environment variables
  • Assuming $Error stores user inputs
2. Which of the following is the correct way to clear all errors stored in $Error?
easy
A. Clear-Error
B. $Error = $null
C. $Error.Clear()
D. Remove-Variable $Error

Solution

  1. Step 1: Identify the method to clear errors

    $Error is an automatic variable with a method Clear() to empty its contents.
  2. Step 2: Evaluate other options

    Assigning $null or removing the variable does not properly clear the error collection; Clear-Error is not a valid cmdlet.
  3. Final Answer:

    $Error.Clear() -> Option C
  4. Quick Check:

    Use $Error.Clear() to clear errors [OK]
Hint: Use $Error.Clear() to empty errors quickly [OK]
Common Mistakes:
  • Trying to assign $null to $Error
  • Using non-existent cmdlets like Clear-Error
  • Removing $Error variable instead of clearing
3. Given this PowerShell code:
Try { Get-Item 'C:\nonexistentfile.txt' } Catch { Write-Host 'Error caught' }
$latestError = $Error[0]
Write-Output $latestError.Exception.Message

What will be the output?
medium
A. Error caught
B. Cannot find path 'C:\nonexistentfile.txt' because it does not exist.
C. No errors found
D. Get-Item : The term 'Get-Item' is not recognized

Solution

  1. Step 1: Understand the Try-Catch block behavior

    The command tries to get a file that does not exist, causing an error caught by Catch, which writes 'Error caught'.
  2. Step 2: Analyze $Error[0] and output

    $Error[0] holds the most recent error object. Accessing Exception.Message outputs the detailed error message about the missing file.
  3. Final Answer:

    Cannot find path 'C:\nonexistentfile.txt' because it does not exist. -> Option B
  4. Quick Check:

    $Error[0].Exception.Message shows error details [OK]
Hint: Remember $Error[0] is newest error object [OK]
Common Mistakes:
  • Confusing Write-Host output with $Error content
  • Expecting 'Error caught' from Write-Host as output
  • Assuming no error is stored in $Error
4. You run this code:
Get-Item 'C:\missingfile.txt'
Write-Output $Error[0]

But the output is empty. What is the likely reason?
medium
A. The error was cleared before accessing $Error
B. Get-Item succeeded, so no error was recorded
C. $Error variable is not available in this session
D. You must use $Errors instead of $Error

Solution

  1. Step 1: Check if error occurred

    Since the file is missing, Get-Item should cause an error and populate $Error.
  2. Step 2: Consider why $Error[0] is empty

    If $Error was cleared (e.g., by $Error.Clear()) before accessing, it will be empty despite the error.
  3. Final Answer:

    The error was cleared before accessing $Error -> Option A
  4. Quick Check:

    Clearing $Error empties error list [OK]
Hint: Check if $Error was cleared before reading it [OK]
Common Mistakes:
  • Assuming $Error is empty if no error occurred
  • Confusing $Error with $Errors variable
  • Thinking $Error is unavailable in session
5. You want to write a script that tries to get a file, and if it fails, clears the error list and logs the error message only once. Which code snippet correctly uses $Error to achieve this?
hard
A.
Try { Get-Item 'C:\file.txt' } Catch { $Error.Clear(); Write-Output $Error[0].Exception.Message }
B.
Try { Get-Item 'C:\file.txt' } Catch { Write-Output $Error.Clear(); Write-Output $Error[0].Exception.Message }
C.
Get-Item 'C:\file.txt' -ErrorAction SilentlyContinue; Write-Output $Error[0].Exception.Message; $Error.Clear()
D.
Try { Get-Item 'C:\file.txt' } Catch { $msg = $Error[0].Exception.Message; $Error.Clear(); Write-Output $msg }

Solution

  1. Step 1: Identify correct error handling and clearing order

    Try { Get-Item 'C:\file.txt' } Catch { $msg = $Error[0].Exception.Message; $Error.Clear(); Write-Output $msg }
    captures the error message from $Error[0], then clears the error list, then outputs the message.
  2. Step 2: Check other options for mistakes

    Try { Get-Item 'C:\file.txt' } Catch { Write-Output $Error.Clear(); Write-Output $Error[0].Exception.Message }
    clears errors before reading message (wrong order).
    Get-Item 'C:\file.txt' -ErrorAction SilentlyContinue; Write-Output $Error[0].Exception.Message; $Error.Clear()
    does not use Try-Catch and may fail silently.
    Try { Get-Item 'C:\file.txt' } Catch { $Error.Clear(); Write-Output $Error[0].Exception.Message }
    clears errors before reading message, losing the error.
  3. Final Answer:

    Try { Get-Item 'C:\file.txt' } Catch { $msg = $Error[0].Exception.Message; $Error.Clear(); Write-Output $msg } -> Option D
  4. Quick Check:

    Read error before clearing $Error [OK]
Hint: Always read $Error before calling $Error.Clear() [OK]
Common Mistakes:
  • Clearing $Error before reading error message
  • Not using Try-Catch for error handling
  • Expecting $Error to update immediately without Try-Catch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard