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?$Error to achieve this?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.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.15+ quiz questions · All difficulty levels · Free
Free Signup - Practice All Questions