0
0
PowerShellscripting~5 mins

Error logging patterns in PowerShell

Choose your learning style9 modes available
Introduction

Error logging helps you find and fix problems by saving details about what went wrong.

When running scripts that might fail and you want to know why.
When automating tasks and need to keep a record of errors for later review.
When debugging a script that behaves unexpectedly.
When you want to alert someone or take action if an error happens.
When you want to keep your script running even if some parts fail.
Syntax
PowerShell
try {
  # Code that might cause an error
} catch {
  # Code to handle the error
  Write-Error "Error message"
  Add-Content -Path error.log -Value $_.Exception.Message
}

try runs code that might fail.

catch runs if an error happens, letting you log or handle it.

Examples
This tries to get a file. If it doesn't exist, it shows an error message.
PowerShell
try {
  Get-Item 'C:\nonexistentfile.txt'
} catch {
  Write-Error "File not found: $_"
}
This tries to divide by zero, catches the error, and writes it to a log file.
PowerShell
try {
  $result = 1 / 0
} catch {
  Add-Content -Path 'error.log' -Value "Divide by zero error: $_"
}
This tries to get a web page. On failure, it logs the error with a timestamp.
PowerShell
try {
  Invoke-WebRequest 'http://badurl'
} catch {
  Write-Error "Web request failed: $_"
  Add-Content -Path 'error.log' -Value "$(Get-Date): $_"
}
Sample Program

This script tries to read a file. If it fails, it logs the error with the date and time to a file and shows an error message.

PowerShell
try {
  # Attempt to read a file that may not exist
  $content = Get-Content 'C:\temp\data.txt'
  Write-Output "File content loaded successfully."
} catch {
  # Log error message with timestamp
  $errorMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Error reading file: $($_.Exception.Message)"
  Add-Content -Path 'C:\temp\error.log' -Value $errorMessage
  Write-Error $errorMessage
}
OutputSuccess
Important Notes

Use try/catch to keep your script from stopping on errors.

Log errors with timestamps to track when problems happen.

Use Write-Error to show errors clearly in the console.

Summary

Error logging helps find and fix script problems.

Use try/catch blocks to catch and log errors.

Always add timestamps to error logs for better tracking.