Function for Powershell to test if TCP port answers

function Test-Port($hostname, $port)
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    } catch {}



Leave a Reply

Your email address will not be published. Required fields are marked *