📖 Scenario: You are managing a PowerShell script that runs several commands. You want to capture errors in a structured way to help troubleshoot issues later.
🎯 Goal: Build a PowerShell script that runs commands, logs errors into a dictionary with error messages and counts, and then displays the error summary.
📋 What You'll Learn
Create a dictionary to store error messages and their counts
Add a variable to hold the list of commands to run
Run each command and catch errors, updating the dictionary
Print the error summary with messages and counts
💡 Why This Matters
🌍 Real World
Scripts often run multiple commands where some may fail. Logging errors helps track and fix issues efficiently.
💼 Career
Error logging is a key skill for DevOps engineers to maintain reliable automation scripts and troubleshoot failures.
Progress0 / 4 steps
1
Create the error log dictionary
Create a dictionary called $ErrorLog initialized as an empty hashtable to store error messages and their counts.
PowerShell
Hint
Use @{} to create an empty hashtable in PowerShell.
2
Define commands to run
Create a variable called $Commands and assign it an array with these exact strings: 'Get-Process', 'Get-Service', and 'Get-NonExistentCommand'.
PowerShell
Hint
Use @( ... ) to create an array in PowerShell.
3
Run commands and log errors
Use a foreach loop with variable $cmd to iterate over $Commands. Inside the loop, run Invoke-Expression $cmd inside a try block. Catch errors in a catch block. In the catch block, get the error message from $_.Exception.Message. If the message is already a key in $ErrorLog, increment its value by 1; otherwise, add it with value 1.
PowerShell
Hint
Use try { ... } catch { ... } to handle errors in PowerShell.
Use Invoke-Expression to run the command string.
4
Print the error summary
Use a foreach loop with variables $message and $count to iterate over $ErrorLog.GetEnumerator(). Inside the loop, print the error message and count in the format: Error: {message} - Count: {count} using Write-Output.
PowerShell
Hint
Use $ErrorLog.GetEnumerator() to loop over hashtable keys and values.
Use Write-Output to print lines.
Practice
(1/5)
1. What is the main purpose of using try/catch blocks in PowerShell scripts for error logging?
easy
A. To automatically fix errors
B. To speed up script execution
C. To catch errors and handle them gracefully
D. To ignore all errors silently
Solution
Step 1: Understand the role of try/catch
The try block runs code that might cause errors, and the catch block handles those errors.
Step 2: Purpose of error handling
Using try/catch helps scripts manage errors without stopping abruptly, allowing logging or recovery.
Final Answer:
To catch errors and handle them gracefully -> Option C
Quick Check:
Error handling = catch errors [OK]
Hint: Try/catch blocks catch and handle errors safely [OK]
Common Mistakes:
Thinking try/catch fixes errors automatically
Believing try/catch speeds up scripts
Assuming try/catch ignores errors
2. Which of the following is the correct syntax to write an error message with a timestamp to a log file in PowerShell?
easy
A. Add-Content error.log "$(Get-Date): Error occurred"
B. Write-Error "$(Get-Date): Error occurred" >> error.log
C. Write-Output "Error occurred at $(Get-Date)" > error.log
D. Write-Host "$(Get-Date): Error occurred" >> error.log
Solution
Step 1: Identify correct cmdlet for appending text
Add-Content appends text to a file without overwriting it, suitable for logging.
Step 2: Check timestamp and message format
Using "$(Get-Date): Error occurred" correctly adds a timestamp and message.
Final Answer:
Add-Content error.log "$(Get-Date): Error occurred" -> Option A
Quick Check:
Append log with Add-Content [OK]
Hint: Use Add-Content to append logs with timestamps [OK]
Common Mistakes:
Using Write-Error which writes to error stream, not file
Using Write-Host which outputs to console only
Using > which overwrites the file instead of appending
3. What will be the output of this PowerShell snippet?
try {
Get-Item 'C:\nonexistentfile.txt'
} catch {
Add-Content error.log "$(Get-Date): File not found error"
'Error logged'
}
medium
A. No output, only error.log updated
B. Error logged
C. File not found error
D. Script stops with error
Solution
Step 1: Analyze try block
The command tries to get a file that does not exist, causing an error.
Step 2: Analyze catch block
The catch block appends a timestamped error message to error.log and outputs the string 'Error logged'.
Final Answer:
Error logged -> Option B
Quick Check:
Catch outputs message after logging [OK]
Hint: Catch block outputs text after logging error [OK]
Common Mistakes:
Thinking no output appears because only file is updated
Expecting script to stop on error
Confusing error message with output string
4. Identify the error in this PowerShell error logging snippet:
B. Write-Error should be replaced with Write-Host to log properly
C. Try block syntax is incorrect
D. Add-Content should include timestamp for better logs
Solution
Step 1: Review logging commands
Write-Error writes to error stream, which is okay for alerting, but Add-Content logs to file without timestamp.
Step 2: Importance of timestamps in logs
Logs without timestamps make tracking errors over time difficult; adding $(Get-Date) improves log usefulness.
Final Answer:
Add-Content should include timestamp for better logs -> Option D
Quick Check:
Logs need timestamps for clarity [OK]
Hint: Always add timestamps when logging errors to files [OK]
Common Mistakes:
Thinking Write-Error cannot be used in catch
Ignoring importance of timestamps in logs
Assuming try block syntax is wrong
5. You want to create a PowerShell script that logs errors with timestamps and the error message to a file, but only if the error is not a 'FileNotFoundException'. Which pattern correctly implements this?