Introduction
Error logging helps you find and fix problems by saving details about what went wrong.
Error logging helps you find and fix problems by saving details about what went wrong.
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.
try {
Get-Item 'C:\nonexistentfile.txt'
} catch {
Write-Error "File not found: $_"
}try {
$result = 1 / 0
} catch {
Add-Content -Path 'error.log' -Value "Divide by zero error: $_"
}try {
Invoke-WebRequest 'http://badurl'
} catch {
Write-Error "Web request failed: $_"
Add-Content -Path 'error.log' -Value "$(Get-Date): $_"
}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.
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
}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.
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.
try/catch blocks in PowerShell scripts for error logging?try block runs code that might cause errors, and the catch block handles those errors.try/catch helps scripts manage errors without stopping abruptly, allowing logging or recovery.Add-Content appends text to a file without overwriting it, suitable for logging."$(Get-Date): Error occurred" correctly adds a timestamp and message.try {
Get-Item 'C:\nonexistentfile.txt'
} catch {
Add-Content error.log "$(Get-Date): File not found error"
'Error logged'
}try {
Get-Content 'C:\missing.txt'
} catch {
Write-Error "$(Get-Date): File missing"
Add-Content error.log "File missing"
}Write-Error writes to error stream, which is okay for alerting, but Add-Content logs to file without timestamp.$(Get-Date) improves log usefulness.FileNotFoundException allows ignoring that specific error.Pass the test and this pattern moves unknown