0
0
PowerShellscripting~10 mins

Error logging patterns in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Error logging patterns
Start Script
Try Block
Execute Command
Error?
YesCatch Block
Log Error
Optional: Notify
Continue or Exit
The script tries to run commands, catches errors if they happen, logs them, and optionally notifies before continuing or exiting.
Execution Sample
PowerShell
try {
  Get-Item 'C:\nonexistentfile.txt'
} catch {
  Write-Error "Error: $_"
  Add-Content -Path 'error.log' -Value "$(Get-Date): $_"
}
This script tries to get a file, logs an error message if it fails, and writes the error details to a log file.
Execution Table
StepActionCommand/ExpressionResultOutput/Log
1Start try blockGet-Item 'C:\nonexistentfile.txt'File not found error thrown
2Catch error$_Contains error details
3Write error to consoleWrite-Error "Error: $_"Error message displayedError: Cannot find path 'C:\nonexistentfile.txt' because it does not exist.
4Log error to fileAdd-Content -Path 'error.log' -Value "$(Get-Date): $_"Error appended to error.logLog file updated with timestamp and error
5End scriptScript ends after logging
💡 Error caught and logged, script ends gracefully without crashing
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
$_nullnullErrorRecord object with file not found messageSame ErrorRecord objectSame ErrorRecord object
Key Moments - 3 Insights
Why does the script not crash when the file is missing?
Because the error is caught in the catch block (see execution_table step 2), preventing the script from stopping unexpectedly.
What does the variable $_ represent in the catch block?
It holds the error details caught by the catch block (see variable_tracker after step 2), which we use to log and display the error.
How does the script log the error to a file?
Using Add-Content to append a timestamped error message to 'error.log' (see execution_table step 4), so errors are recorded for later review.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 3?
AFile content printed
BError message displayed on console
CNo output
DScript crashes
💡 Hint
Check the 'Output/Log' column at step 3 in the execution_table
At which step does the script write the error to the log file?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for 'Log error to file' action in the execution_table
If the file exists, what happens to the catch block?
AIt is skipped, no error occurs
BIt runs and logs an error
CIt runs but logs no error
DScript crashes
💡 Hint
Catch block only runs if an error occurs, see concept_flow and execution_table step 1
Concept Snapshot
PowerShell error logging pattern:
try { <command> } catch { <handle error> }
Use $_ in catch to access error details.
Log errors with Add-Content to a file.
Prevents script crashes by handling errors gracefully.
Full Transcript
This PowerShell script tries to get a file. If the file does not exist, an error occurs. The catch block catches this error and stores it in $_. The script then writes an error message to the console and appends the error details with a timestamp to a log file named error.log. This pattern helps keep scripts running smoothly by handling errors and recording them for later review.