Bird
0
0

You want to write a script that tries to get a file, and if it fails, clears the error list and logs the error message only once. Which code snippet correctly uses $Error to achieve this?

hard📝 Application Q15 of 15
PowerShell - Error Handling
You want to write a script that tries to get a file, and if it fails, clears the error list and logs the error message only once. Which code snippet correctly uses $Error to achieve this?
A<pre>Try { Get-Item 'C:\file.txt' } Catch { $Error.Clear(); Write-Output $Error[0].Exception.Message }</pre>
B<pre>Try { Get-Item 'C:\file.txt' } Catch { Write-Output $Error.Clear(); Write-Output $Error[0].Exception.Message }</pre>
C<pre>Get-Item 'C:\file.txt' -ErrorAction SilentlyContinue; Write-Output $Error[0].Exception.Message; $Error.Clear()</pre>
D<pre>Try { Get-Item 'C:\file.txt' } Catch { $msg = $Error[0].Exception.Message; $Error.Clear(); Write-Output $msg }</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct error handling and clearing order

    Try { Get-Item 'C:\file.txt' } Catch { $msg = $Error[0].Exception.Message; $Error.Clear(); Write-Output $msg }
    captures the error message from $Error[0], then clears the error list, then outputs the message.
  2. Step 2: Check other options for mistakes

    Try { Get-Item 'C:\file.txt' } Catch { Write-Output $Error.Clear(); Write-Output $Error[0].Exception.Message }
    clears errors before reading message (wrong order).
    Get-Item 'C:\file.txt' -ErrorAction SilentlyContinue; Write-Output $Error[0].Exception.Message; $Error.Clear()
    does not use Try-Catch and may fail silently.
    Try { Get-Item 'C:\file.txt' } Catch { $Error.Clear(); Write-Output $Error[0].Exception.Message }
    clears errors before reading message, losing the error.
  3. Final Answer:

    Try { Get-Item 'C:\file.txt' } Catch { $msg = $Error[0].Exception.Message; $Error.Clear(); Write-Output $msg } -> Option D
  4. Quick Check:

    Read error before clearing $Error [OK]
Quick Trick: Always read $Error before calling $Error.Clear() [OK]
Common Mistakes:
  • Clearing $Error before reading error message
  • Not using Try-Catch for error handling
  • Expecting $Error to update immediately without Try-Catch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes