Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try & Catch not working when using Invoke-Command

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?

like image 775
SimonS Avatar asked Dec 18 '22 20:12

SimonS


1 Answers

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"
}
like image 52
briantist Avatar answered Feb 16 '23 21:02

briantist