0
0
PowerShellscripting~20 mins

$Error automatic variable in PowerShell - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PowerShell Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What does the $Error variable contain after a failed command?
Consider this PowerShell snippet:
$Error.Clear()
Get-Item nonexistentfile.txt
$Error[0]

What will be the output of $Error[0]?
PowerShell
$Error.Clear()
Get-Item nonexistentfile.txt
$Error[0]
AAn empty string because $Error was cleared before the command.
BAn error record object describing the failure to find 'nonexistentfile.txt'.
CThe string 'nonexistentfile.txt' because it is the name of the missing file.
DA null value because $Error does not store errors from Get-Item.
Attempts:
2 left
💡 Hint
Remember that $Error stores error objects from commands that fail, even after clearing.
💻 Command Output
intermediate
2:00remaining
How many errors are stored in $Error after multiple failures?
Run this code:
$Error.Clear()
Get-Item missing1.txt
Get-Item missing2.txt
$Error.Count

What is the value of $Error.Count?
PowerShell
$Error.Clear()
Get-Item missing1.txt
Get-Item missing2.txt
$Error.Count
AAn error because $Error.Count is invalid
B1
C0
D2
Attempts:
2 left
💡 Hint
Each failed command adds one error record to $Error.
📝 Syntax
advanced
2:00remaining
Which option correctly clears the $Error variable?
You want to clear all previous errors stored in $Error. Which command is correct?
A$Error.Clear()
B$Error = $null
CClear-Variable $Error
D$Error.RemoveAll()
Attempts:
2 left
💡 Hint
Think about the method that empties the error collection without removing the variable.
🔧 Debug
advanced
2:00remaining
Why does this code not clear $Error as expected?
Given this code:
$Error = $null
Get-Item missingfile.txt
$Error.Count

What will happen and why?
PowerShell
$Error = $null
Get-Item missingfile.txt
$Error.Count
AIt throws an error because $Error is null and does not have a Count property.
BIt outputs 1 because the error is added to $Error automatically.
CIt outputs 0 because $Error was set to null before the command.
DIt outputs the number of errors from previous commands.
Attempts:
2 left
💡 Hint
Consider what happens when you overwrite $Error with $null.
🚀 Application
expert
2:00remaining
How to retrieve the error message text from the latest error in $Error?
You want to get just the error message string from the most recent error stored in $Error. Which command will output only the error message text?
A$Error[0].Message
B$Error[0].ToString()
C$Error[0].Exception.Message
D$Error[0].ErrorDetails.Message
Attempts:
2 left
💡 Hint
The error record contains an Exception object with the message property.