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