Bird
0
0

Which code snippet correctly implements this?

hard📝 Application Q8 of 15
PowerShell - Error Handling
You want to write a PowerShell script that attempts to read a file and, if it fails, writes a custom error message to a log file instead of displaying it on the console. Which code snippet correctly implements this?
Atry { Get-Content 'log.txt' } catch { Write-Host "Error reading file: $_" }
Btry { Get-Content 'log.txt' } catch { "Error reading file: $_" | Out-File 'error.log' -Append }
CGet-Content 'log.txt' -ErrorAction SilentlyContinue Write-Host "Error reading file"
Dtry { Get-Content 'log.txt' } catch { Write-Error "Error reading file" }
Step-by-Step Solution
Solution:
  1. Step 1: Use try-catch to handle errors

    The try block attempts to read the file.
  2. Step 2: In catch, write error message to log file

    Using Out-File with -Append writes the message to 'error.log' without console output.
  3. Final Answer:

    try { Get-Content 'log.txt' } catch { "Error reading file: $_" | Out-File 'error.log' -Append } -> Option B
  4. Quick Check:

    Catch block writes error to file, not console [OK]
Quick Trick: Pipe error message to Out-File with -Append in catch [OK]
Common Mistakes:
  • Using Write-Host which outputs to console
  • Ignoring error handling and logging
  • Using Write-Error which also outputs to console

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes