try, catch doesent seem to work


I have the following code which I thought would allow me to catch an error and instead of generating the error write out “An Error Occurred”.

Unfortunately, it still shows the error “Failed to restart the computer: Access is denied” instead.

I know why this is happening but I want to be able to catch the error and reformat it. What am I doing wrong?


In PowerShell there are terminating and non-terminating errors. The former terminate script execution (if not caught) and can be caught by try..catch, the latter don’t terminate script execution (so there’s nothing to catch). The error you’re receiving is a non-terminating one, so you need to make it a terminating error by appending -ErrorAction Stop to the statement:

Alternatively you can set $ErrorActionPreference = "Stop" if you want all errors to become terminating errors.

See this article on the Scripting Guy blog for more information.


try, catch doesent seem to work by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply