PowerShell: Can’t catch UnauthorizedAccessException thrown by get-content

Question:

I am trying to catch the System.UnauthorizedAccessException. This exception occurs if a user has no read-access to a specific file.

But I keep getting this error message:

What am I doing wrong here?


Thanks for answering. I still don’t understand why this run’s into [Exception] and not into the more specific [System.UnauthorizedAccessException].

Answer:

try/catch will catch only terminating errors.
You can use the following command on top of your script to make all errors a terminating error

$erroractionPreference="stop"

@Shay Levy has the explaination here : https://stackoverflow.com/a/8381798/381149

Source:

PowerShell: Can’t catch UnauthorizedAccessException thrown by get-content by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply