Bird
Raised Fist0
PowerShellscripting~20 mins

Error logging patterns in PowerShell - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PowerShell Error Logging Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
PowerShell Error Logging Output
What is the output of this PowerShell script when the command fails?
$ErrorActionPreference = 'Stop'
try {
  Get-Item 'C:\nonexistentfile.txt'
} catch {
  Write-Output "Error caught: $_"
}
PowerShell
$ErrorActionPreference = 'Stop'
try {
  Get-Item 'C:\nonexistentfile.txt'
} catch {
  Write-Output "Error caught: $_"
}
AError caught: Cannot find path 'C:\nonexistentfile.txt' because it does not exist.
BGet-Item : Cannot find path 'C:\nonexistentfile.txt' because it does not exist.
CNo output, script runs silently.
DError caught: The term 'Get-Item' is not recognized as the name of a cmdlet.
Attempts:
2 left
💡 Hint
Look at how the try-catch block handles errors with Write-Output.
✅ Best Practice
intermediate
2:00remaining
Best Practice for Logging Errors in PowerShell
Which option is the best practice for logging errors in a PowerShell script to a file with timestamps?
AUse Write-Error with Out-File to append errors: Write-Error $_ | Out-File errors.log -Append
BUse Write-Output inside catch block without timestamps: Write-Output $_
CUse Write-Host to display errors and redirect output to a file: Write-Host $_ > errors.log
DUse try-catch and inside catch use Add-Content with timestamp: Add-Content errors.log "$(Get-Date): $_"
Attempts:
2 left
💡 Hint
Consider how to add timestamps and append to a file safely.
❓ Troubleshoot
advanced
2:00remaining
Troubleshooting Missing Error Logs
A PowerShell script uses this code to log errors:
try {
  Remove-Item 'C:\temp\file.txt'
} catch {
  $_ | Out-File 'error.log'
}

Why might the error.log file be empty after a failure?
PowerShell
try {
  Remove-Item 'C:\temp\file.txt'
} catch {
  $_ | Out-File 'error.log'
}
AThe script lacks permissions to write to error.log, so file stays empty.
BRemove-Item does not throw an error if the file is missing, so catch never runs.
COut-File overwrites the file but $_ is an error object, not a string, so nothing is written.
DThe error variable $_ is empty because errors are non-terminating by default.
Attempts:
2 left
💡 Hint
Consider whether the error from Remove-Item is terminating or non-terminating.
🔀 Workflow
advanced
2:00remaining
PowerShell Error Logging Workflow
Which sequence correctly describes a workflow to log errors with timestamps and continue script execution?
A1,2,3,4
B2,1,3,4
C1,3,2,4
D2,3,1,4
Attempts:
2 left
💡 Hint
Think about setting error preference before running commands.
🧠 Conceptual
expert
2:00remaining
Understanding PowerShell Error Variable Behavior
In PowerShell, what is the difference between using $_ and $Error[0] inside a catch block for error logging?
A$_ is only available outside catch blocks; $Error[0] is only available inside catch blocks.
B$_ and $Error[0] always contain the exact same error object inside catch blocks.
C$_ contains the current error object in catch; $Error[0] is the most recent error in the global error array, which may differ.
D$_ is a string of the error message; $Error[0] is the full error object with details.
Attempts:
2 left
💡 Hint
Consider the scope and timing of these variables.

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

  1. Step 1: Understand the role of try/catch

    The try block runs code that might cause errors, and the catch block handles those errors.
  2. Step 2: Purpose of error handling

    Using try/catch helps scripts manage errors without stopping abruptly, allowing logging or recovery.
  3. Final Answer:

    To catch errors and handle them gracefully -> Option C
  4. 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

  1. Step 1: Identify correct cmdlet for appending text

    Add-Content appends text to a file without overwriting it, suitable for logging.
  2. Step 2: Check timestamp and message format

    Using "$(Get-Date): Error occurred" correctly adds a timestamp and message.
  3. Final Answer:

    Add-Content error.log "$(Get-Date): Error occurred" -> Option A
  4. 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

  1. Step 1: Analyze try block

    The command tries to get a file that does not exist, causing an error.
  2. Step 2: Analyze catch block

    The catch block appends a timestamped error message to error.log and outputs the string 'Error logged'.
  3. Final Answer:

    Error logged -> Option B
  4. 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:
try {
  Get-Content 'C:\missing.txt'
} catch {
  Write-Error "$(Get-Date): File missing"
  Add-Content error.log "File missing"
}
medium
A. Catch block should not write to error stream
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

  1. Step 1: Review logging commands

    Write-Error writes to error stream, which is okay for alerting, but Add-Content logs to file without timestamp.
  2. Step 2: Importance of timestamps in logs

    Logs without timestamps make tracking errors over time difficult; adding $(Get-Date) improves log usefulness.
  3. Final Answer:

    Add-Content should include timestamp for better logs -> Option D
  4. 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?
hard
A. try { # code } catch [System.IO.FileNotFoundException] { # ignore } catch { Add-Content error.log "$(Get-Date): $_" }
B. try { # code } catch { if ($_ -notlike '*FileNotFoundException*') { Add-Content error.log "$(Get-Date): $_" } }
C. try { # code } catch { Add-Content error.log "$(Get-Date): $_" }
D. try { # code } catch [System.Exception] { Add-Content error.log "$(Get-Date): $_" }

Solution

  1. Step 1: Understand exception filtering

    Using a typed catch block for FileNotFoundException allows ignoring that specific error.
  2. Step 2: Use a general catch for other errors

    The second catch block logs all other errors with timestamp and message.
  3. Final Answer:

    Typed catch ignores FileNotFoundException; general catch logs others -> Option A
  4. Quick Check:

    Typed catch filters errors correctly [OK]
Hint: Use typed catch to skip specific errors [OK]
Common Mistakes:
  • Logging all errors without filtering
  • Using if condition incorrectly inside catch
  • Not using typed catch blocks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard