Test NetConnection - PowerShell


Overview

Test-NetConnection is a robust PowerShell command that evaluates network connectivity by sending ICMP or TCP packets to a remote host. It determines whether hosts or specific ports are accessible, providing valuable insights for troubleshooting and network management tasks.

Syntax

Test-NetConnection [-ComputerName] <String> -Port <Int32> [-Count <Int32>] [-Delay <Int32>] 
[-Quiet] [-WarningAction <WarningAction>] [-ErrorAction <ErrorAction>]

Options/Flags

  • -ComputerName: Specifies the host to test connectivity to. Use FQDN or IP address.
  • -Port: Specifies the TCP or UDP port to test. Required for TCP and UDP tests.
  • -Count: Sets the number of packets to send during the test. Default is 3.
  • -Delay: Specifies the interval (in milliseconds) between sending packets. Default is 1000.
  • -Quiet: Suppresses unnecessary output, showing only error or warning messages.
  • -WarningAction: Defines the action to take when warnings occur.
  • -ErrorAction: Defines the action to take when errors occur.

Examples

Simple ICMP Test:

Test-NetConnection -ComputerName www.example.com

TCP Port Test:

Test-NetConnection -ComputerName mail.example.com -Port 25

UDP Port Test with multiple retries:

Test-NetConnection -ComputerName gateway.example.com -Port 161 -Count 10 -Delay 500

Silent Test (no output unless error):

Test-NetConnection -ComputerName server1.example.com -Port 8080 -Quiet

Common Issues

  • Using IP addresses that are not resolvable by DNS may cause errors.
  • Incorrect port numbers or unsupported protocols can lead to test failures.
  • Firewalls can block test packets, resulting in connection failures.

Integration

Combine with Ping Command:

$ping = Ping google.com
if ($ping) { Test-NetConnection -ComputerName google.com -Port 80 }

Use in Scripting:

$hosts = Get-Content "hostnames.txt"
foreach ($host in $hosts) {
    $result = Test-NetConnection -ComputerName $host -Port 443
    if ($result.StatusCode -eq "Success") { Write-Host "$host is reachable" }
}
  • Ping: Performs ICMP echo requests for connectivity tests.
  • Get-NetIPConfiguration: Obtains IP configuration details of network interfaces.
  • Invoke-WebRequest: Sends HTTP requests for web connectivity checks.