Try & Catch not working when using Invoke-Command

Question:

There’s a strange issue in my script.
I’m invoking a command on some servers. If I can’t connect to the server (because it’s offline or something) I still want to log that (Server is offline > log.txt)

Apparently, when an error occurs in Try block, the Catch block is not executed.

To test this, I wrote a value to the ComputerName parameter that doesn’t exist.
Here’s my code:

But the Script never puts out “Hello”

The exception I get is a PSRemotingTransportException. I also tried to specify the exception, also didn’t work

When I set a breakpoint at the Invoke-Command line, it also ignores the catch block. Why?

Answer:

It’s not a terminating error, so it will never be caught by try/catch. Add -ErrorAction Stop:

Source:

Try & Catch not working when using Invoke-Command by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply