Windows admin PowerShell

Test if a TCP port is open on a list of servers

Check one or more TCP ports on a list of servers with a short timeout. It is much faster than Test-NetConnection on hosts that do not answer.

LanguagePowerShell
What it does to the systemReads only. It changes nothing.

Is the firewall open? Test-NetConnection answers, but it waits a long time on each closed port. On a list of servers that takes minutes.

This script tries a plain TCP connection with a timeout you choose. It returns one line per server and port.

PowerShell
<#
  Test TCP ports on a list of servers.
  Needs no special rights. It only opens a connection and closes it.
  Example: .\Test-TcpPort.ps1 -ComputerName SRV01, SRV02 -Port 443, 445
#>
param(
    [string[]]$ComputerName = 'localhost',

    [ValidateRange(1, 65535)]
    [int[]]$Port = 445,

    # How long to wait for an answer, in milliseconds.
    [int]$TimeoutMs = 2000
)

foreach ($computer in $ComputerName) {
    foreach ($number in $Port) {
        $client = New-Object System.Net.Sockets.TcpClient
        $open = $false
        try {
            $attempt = $client.BeginConnect($computer, $number, $null, $null)
            # Wait for the connection, but not longer than the timeout.
            if ($attempt.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) {
                $client.EndConnect($attempt)
                $open = $client.Connected
            }
        }
        catch {
            # Refused, or the name does not resolve. The port counts as closed.
            $open = $false
        }
        finally {
            $client.Close()
        }
        [pscustomobject]@{ ComputerName = $computer; Port = $number; Open = $open }
    }
}

How to use it

  1. Save the script as Test-TcpPort.ps1.
  2. Run .\Test-TcpPort.ps1 -ComputerName SRV01 -Port 443.
  3. Give more ports with commas: -Port 80, 443, 8530.
  4. For a list, use -ComputerName (Get-Content C:\Temp\servers.txt) with one name per line.
  5. Raise -TimeoutMs for slow links.

Good to know

  • Run it from the computer that needs the connection. A firewall can allow one source and block another.
  • Open means a program listens and the path is clear. Closed can mean a firewall, a stopped service or a wrong name.
  • The script tests TCP only. It cannot test UDP ports.
TCP port port test firewall TcpClient Test-NetConnection
✉

Get new articles in your inbox

SCCM guides, AI tools, automation tips — sent when published. No spam.