How to error handle Invoke-Command over SSH

Nanne14 20 Reputation points
2023-11-30T15:48:42.5933333+00:00

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 halts, and I have to manually abort it.

So as the script just stops I do not know how to handle such an error as following code just does not get executed. Is there any recommended approach or fix to implement proper exception handling in such cases?

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2023-11-30T16:03:39.8066667+00:00

    After the Invoke-Command, what follows next in the script? Are you checking the output from the Invoke-Command?

    If you want to get the output, including any errors, try redirecting the error stream (a.k.a., STDERR) to the success stream (a.k.a., STDOUT)

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

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-5.1


  2. Rich Matheisen 47,901 Reputation points
    2023-11-30T16:31:01.86+00:00

    Your Invoke-Command is never run! Replace "-HostName" with "-ComputerName".

    Invoke-Command : A parameter cannot be found that matches parameter name 'HostName'.
    At C:\Projects\Exercism\work.ps1:1 char:26
    + $result = Invoke-Command -HostName '192.168.100.1' -ScriptBlock { Wri ...
    +                          ~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
        + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
    

    If the machine at the IP address isn't accepting connections the Invoke-Command will either return after the attempt at connecting times out (a function of your client machine's network) or, if the address isn't reachable, it will fail very quickly.

    If the Invoke-Command fails, the $result variable will hold an object with the type "ErrorRecord" that will provide the details.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.