powershellsshpowershell-remotinginvoke-commandpowershell-7.0

How to error handle Invoke-Command over SSH


I'm currently working with a script that utilizes the Invoke-Command over SSH as shown below. While it works well, I'm looking to implement exception handling, specifically for scenarios where the remote server is not reachable. Invoke-Command -HostName '192.168.100.1' -ScriptBlock { Write-Output "Hi" }

When the remote server is not reachable, I receive the following error message: "ssh: connect to host 192.168.100.1 port 22: Connection timed out".

The challenge is that the script just halts and I have no option to manually abort it. So as the script just stops I cannot check for this error message in a if clause or smth. to handle this as the following code just does not get executed.

Is there any recommended approach or fix to implement proper exception handling in such cases?

*(Due to special Network enviornment I need to use remote Powershell over SSH so because ot that the -HostName instead of -ComputerName Parameter is used.)

I tried redirecting the standard error stream (2) to the standard output stream by appending "2>&1" but still the script just halts and nothing gets saved into the variable.

$result = Invoke-Command -HostName '192.168.100.1' -ScriptBlock { Write-Output "Hi" } 2>&1


Solution

  • $result = Invoke-Command -HostName '192.168.100.1' -ScriptBlock { Write-Output "Hi" } -ConnectingTimeout 5000 -ErrorAction STOP
    

    By adding -ConnectingTimeout Parameter the command does not result in a stuck script and throws an error after the specified time. By adding -ErrorAction STOP and putting it into a try-catch block I was able to handle an unsuccessfull connection.

    try {
        Invoke-Command -HostName '192.168.100.1' -ScriptBlock { Write-Output "Hi" } -ConnectingTimeout 5000 -ErrorAction STOP    
    }
    catch {
        $_
    }
    

    Thanks to Rich M. and MotoX80 from Microsoft Forum for providing the solution. Here our disussion about my issue: How to error handle Invoke-Command over SSH