2

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

1
  • Invoke-Command returns a response. Check the response. If you get a bad response terminate the script. Don't write an an output that cannot be used to stop the script. Commented Dec 1, 2023 at 17:47

1 Answer 1

0
$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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.