Testing a Network Port

by Jul 24, 2015

To see whether you can access a remote computer via a given network port, here is a test function called Test-Port; it takes a remote computer name (or IP address), and optionally a port number and timeout.

The default port is 5985 which is used for PowerShell remoting. The default timeout is 1000ms (1 second).

#requires -Version 1
function Test-Port
{
    Param([string]$ComputerName,$port = 5985,$timeout = 1000)
 
    try
    {
        $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
        $iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
        $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
        if(!$wait)
        {
            $tcpclient.Close()
            return $false
        }
        else
        {
            # Close the connection and report the error if there is one
            
            $null = $tcpclient.EndConnect($iar)
            $tcpclient.Close()
            return $true
        }
    }
    catch 
    {
        $false 
    }
}

So if you’d like to know if a remote computer is enabled for PowerShell remoting, you could simply run:

 
PS> Test-Port -ComputerName TestServer 
False
 

With the default timeout of 1 second, you would have to wait at most 1 second for a response.

Twitter This Tip! ReTweet this Tip!