This project is read-only.

Test-TCPPort

Topics: Archive - Toolkit Extensions
Apr 30, 2014 at 5:51 PM
Commonly need to validate TCP Ports are open during installs. Not actually my code, just adapted it and have found it very useful.
Function Test-TCPPort
{
    param ( [ValidateNotNullOrEmpty()]
    [string] $EndPoint = $(throw "Please specify an EndPoint (Host or IP Address)"),
    [string] $Port = $(throw "Please specify a Port") )
    
    $TimeOut = 1000
    $IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
    $Address = [System.Net.IPAddress]::Parse($IP)
    $Socket = New-Object System.Net.Sockets.TCPClient
    $Connect = $Socket.BeginConnect($Address,$Port,$null,$null)
    if ( $Connect.IsCompleted )
    {
        $Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut,$false)           
        if(!$Wait) 
        {
            $Socket.Close() 
            return $false 
        } 
        else
        {
            $Socket.EndConnect($Connect)
            $Socket.Close()
            return $true
        }
    }
    else
    {
        return $false
    }
}
Coordinator
Apr 30, 2014 at 6:02 PM
Great job. Just a minor point. You might throw in a Write-Log to indicate port testing started and then another to show the result. Always good to keep this sort of stuff in the logs :)