0
0
PowerShellscripting~10 mins

Error logging patterns in PowerShell - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch errors using Try-Catch.

PowerShell
try {
    Get-Content 'file.txt' -ErrorAction Stop
} catch [[1]] {
    Write-Error $_.Exception.Message
}
Drag options to blanks, or click blank then click option'
AException
BError
CErrorAction
DCatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Error' instead of 'Exception' in catch block.
2fill in blank
medium

Complete the code to write error messages to a log file.

PowerShell
try {
    Remove-Item 'data.csv' -ErrorAction Stop
} catch {
    $_.Exception.Message | Out-File -FilePath [1] -Append
}
Drag options to blanks, or click blank then click option'
A'log.txt'
B'output.txt'
C'error.log'
D'data.csv'
Attempts:
3 left
💡 Hint
Common Mistakes
Logging errors to the wrong file name.
3fill in blank
hard

Fix the error in the code to properly log errors with timestamps.

PowerShell
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
try {
    Get-Item 'missing.file' -ErrorAction Stop
} catch {
    "$timestamp - Error: [1]" | Out-File -FilePath 'error.log' -Append
}
Drag options to blanks, or click blank then click option'
A$_.Exception.Message
B$_.Exception
C$_.Error.Message
D$_.Message
Attempts:
3 left
💡 Hint
Common Mistakes
Using $_.Message which is undefined in this context.
4fill in blank
hard

Fill both blanks to create a function that logs errors with severity and message.

PowerShell
function Log-Error {
    param($errorMessage)
    $logEntry = "Severity: [1] - Message: [2]"
    $logEntry | Out-File -FilePath 'error.log' -Append
}
Drag options to blanks, or click blank then click option'
A'High'
B$errorMessage
C'Low'
D'Warning'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string for severity.
5fill in blank
hard

Fill all three blanks to log errors with timestamp, severity, and message in a script.

PowerShell
$time = Get-Date -Format 'HH:mm:ss'
$severity = [1]
$errorMsg = [2]
"[$time] Severity: $severity - Error: $errorMsg" | [3] -FilePath 'error.log' -Append
Drag options to blanks, or click blank then click option'
A'Medium'
B$_.Exception.Message
COut-File
D'Critical'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong cmdlet instead of Out-File.