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:
1 2 3 4 5 6 7 |
Try { Invoke-Command -ComputerName hui -ScriptBlock $sb } Catch { Write-Host "Hello" } |
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
:
1 2 3 4 5 6 7 |
Try { Invoke-Command -ComputerName hui -ScriptBlock $sb -ErrorAction Stop } Catch { Write-Host "Hello" } |