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:
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?
It's not a terminating error, so it will never be caught by try
/catch
. Add -ErrorAction Stop
:
Try {
Invoke-Command -ComputerName hui -ScriptBlock $sb -ErrorAction Stop
}
Catch {
Write-Host "Hello"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With