Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Error' instead of 'Exception' in catch block.
✗ Incorrect
The catch block uses Exception to capture error details.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Logging errors to the wrong file name.
✗ Incorrect
Errors are logged to 'error.log' file using Out-File with -Append.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $_.Message which is undefined in this context.
✗ Incorrect
The correct property to get the error message is Exception.Message.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string for severity.
✗ Incorrect
The severity is set to 'High' and the message uses the parameter $errorMessage.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong cmdlet instead of Out-File.
✗ Incorrect
Severity is set to 'Critical', error message is from Exception.Message, and Out-File writes to the log.