0
0
PowerShellscripting~30 mins

Error logging patterns in PowerShell - Mini Project: Build & Apply

Choose your learning style9 modes available
Error Logging Patterns in PowerShell
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use $ErrorLog.GetEnumerator() to loop over hashtable keys and values.

Use Write-Output to print lines.