How to test remote computer connectivity using PowerShell?


To test the remote connectivity using PowerShell Test-Connection command is used. PowerShell also supports the Ping command and both the commands are almost produce the same output but Test- Connection cmdlet supports advanced parameters. See how both commands output look.

Ping Command 

PS C:\Temp> ping Test1-Win2k16
Pinging Test1-Win2k16 [192.168.0.108] with 32 bytes of data:
Reply from 192.168.0.108: bytes=32 time<1ms TTL=128
Reply from 192.168.0.108: bytes=32 time=1ms TTL=128
Reply from 192.168.0.108: bytes=32 time=1ms TTL=128
Reply from 192.168.0.108: bytes=32 time=1ms TTL=128
Ping statistics for 192.168.0.108:
   Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
   Minimum = 0ms, Maximum = 1ms, Average = 0ms

Test-Connection command output

PS C:\Scripts> Test-Connection Test1-win2k16
Source    Destination    IPV4Address    IPV6Address
------    -----------    -----------    -----------
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108

You can reduce the number of checks using -Count parameter. It is similar to -n in the ping command.

 Example

PS C:\Scripts> Test-Connection Test1-win2k16 -Count 2
Source    Destination    IPV4Address    IPV6Address
------    -----------    -----------    -----------
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108

If you need to perform the above command quietly then you can use -Quiet parameter which gives a Boolean (True or False) output if the connection is successful or fails respectively.

PS C:\Scripts> Test-Connection Test1-win2k16 -Count 2 -Quiet
True

Test-Connection has the advantage that it supports common parameters like dealing with errors. In the below example, Any-Comp server doesn’t exist. To catch the error when the server is not reachable or server name doesn’t exist then we will use the ErrorAction parameter supported by cmdlet.

try {
   Test-Connection Any-Comp -Count 2 -ErrorAction Stop
}
catch {
   $_.Exception.Message
}

Output

Testing connection to computer 'Any-Comp' failed: Cannot resolve the target name.

Updated on: 28-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements