← script library

Check If a TCP Port Is Open with PowerShell

Checks & DiagnosticsAugust 17, 2026

Tests one TCP port on one host with a real socket connect and an explicit timeout, rather than a ping that proves nothing about the service. The result is handed to the next runbook step as PortOpen or PortClosed, which makes it a useful gate in front of a deployment or a failover.

powershell
# Check Remote Port
# Single use case: test TCP reachability of one port on one host
#-----------------------------------------------------------------

function Write-Log {
    param($Message)
    Write-Host "<WRITE-LOG = `"*$Message*`">"
}

# --- Parameters (replace via ServerEngine API parameters if needed) ---
$TargetHost = "127.0.0.1"
$TargetPort = 443
$TimeoutMs  = 3000

Write-Log "Testing TCP ${TargetHost}:${TargetPort} (timeout ${TimeoutMs}ms)..."

$client = New-Object System.Net.Sockets.TcpClient
try {
    $async = $client.BeginConnect($TargetHost, [int]$TargetPort, $null, $null)
    $connected = $async.AsyncWaitHandle.WaitOne([int]$TimeoutMs, $false)

    if ($connected -and $client.Connected) {
        Write-Log "OK: ${TargetHost}:${TargetPort} is reachable."
        $store = "PortOpen"
    } else {
        Write-Log "CLOSED: ${TargetHost}:${TargetPort} did not answer within ${TimeoutMs}ms."
        $store = "PortClosed"
    }
} catch {
    Write-Log "CLOSED: ${TargetHost}:${TargetPort} - $($_.Exception.Message)"
    $store = "PortClosed"
} finally {
    $client.Close()
}

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.