Search code examples
powershellpowershell-3.0powershell-4.0

How to test connectivity to a remote computer in powershell


There are two ways suggested in the docs both of which are completely useless to determine if the remote computer is available for powershell remoting.

  1. Test-Connection is useless because it sends only ping, however, the destination may be running Intel AMT and thus respond to ping or may not be running winRM service, so this provides no useful information.

  2. Test-WSMan should test the availability of Windows RM service, but it only works, if the WinRM works, otherwise (the computer is off or WinRM is not running) it gives an error:

    Test-WSMan : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig". At line:2 char:1

    • Test-WSMan -ComputerName destinationcomputer
    • + CategoryInfo          : InvalidOperation: (destinationcomputer:String) [Test-WSMan], InvalidOperationException
      + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.TestWSManCommand
      

So I tried enveloping Test-WSMan in try-catch commands, but it still gives the error out, it is not really caught:

    Try {
         Test-WSMan -ComputerName destinationcomputer
    } catch {
         write-output "not working"}

Any idea how to do this? (i would be happy with Test-WSMan if I could get rid of the error and enforce it to return true or false)


Solution

  • Test $? after running test-wsman.

    Test-WSMan destinationcomputer
    if (! $?) { 
      'not working'
    }
    

    You could also do it this way since a failure returns no standard output:

    if (!(Test-WSMan destinationcomputer)){
      'not working'
    }
    

    See also Check if a command has run successfully

    Also in powershell 7:

    Test-WSMan destinationcomputer || 'not working'