PowerShell Genie

Test a TCP port across servers

Script 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

The loop walks $Computers and calls Test-NetConnection against each with the port held in $Port, capturing the result object.

The script

1PS> $Computers = "SRV01"
2PS> $Port = 443
3PS> foreach($Computer in $Computers){ $r = Test-NetConnection $Computer -Port $Port -WarningAction SilentlyContinue; [pscustomobject]@{Computer= $Computer;Port= $Port;Reachable= $r.TcpTestSucceeded} }

Script reader

Inspect before you run

Inspection only

Inspect the script below. It does not run in this browser.

Inspection only — no command has run.

    Show reference output
    1 ComputerName : SRV01
    2 RemoteAddress : 10.20.30.11
    3 RemotePort : 443
    4 InterfaceAlias : Ethernet
    5 SourceAddress : 10.20.30.41
    6 TcpTestSucceeded : True
    Inspect this example’s structure

    Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

    $Computers = "SRV01" $Port = 443 foreach($Computer in $Computers){ $r = Test-NetConnection $Computer -Port $Port -WarningAction SilentlyContinue; [pscustomobject]@{Computer= $Computer;Port= $Port;Reachable= $r.TcpTestSucceeded} }
    1. Stage 1$ComputersPositional values or no named parameters

      How it works

      The loop walks $Computers and calls Test-NetConnection against each with the port held in $Port, capturing the result object. A [pscustomobject] then records the host name, the port, and TcpTestSucceeded, which is the boolean saying whether the handshake actually completed.

      Adapting it

      Wrap the loop body in Start-ThreadJob or move to a parallel ForEach-Object, since every failing host costs a full TCP timeout and a serial run across fifty targets stretches into minutes.

      If the result is unexpected

      A TCP test fails while a service works from another machine.

      Firewall policy, routing and listening addresses can differ by source and destination.

      1. Run the same host and port check from the affected source and inspect the target listener.

      Validate the result

      The intended source can establish TCP to the expected address and port.

      Keep the check reliable

      Record source host, resolved address and port; a TCP success does not validate the application protocol.

      Primary documentation

      Windows services and processes documentation

      Continue
      Genie guideTest a TCP port across servers

      The loop walks $Computers and calls Test-NetConnection against each with the port held in $Port, capturing the result object.