﻿
function Test-PortConnection ([string]$HostName,$port=135,$timeout=3000,[switch]$verbose)
{
    # Taken from the PowerShell Code Repository (author 'BSonPosh')
    # With some tweaking
    # Does a TCP connection on specified port (135 by default)

    $ErrorActionPreference = "SilentlyContinue"
    $success = $true
    # Create TCP Client
    $tcpclient = new-Object system.Net.Sockets.TcpClient

    # Tell TCP Client to connect to machine on Port
    $iar = $tcpclient.BeginConnect($HostName,$port,$null,$null)

    # Set the wait time
    $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)

    # Check to see if the connection is done
    if(!$wait)
    {
        # Close the connection and report timeout
        $tcpclient.Close()
        if($verbose){Write-Host "Connection Timeout"}
        $success = $false
    }
    else
    {
        # Close the connection and report the error if there is one
        $error.Clear()
        $tcpclient.EndConnect($iar) | out-Null
        if(!$?)
        {
            if($verbose)
            {
                write-host $error[0]
            }
            $success = $false
        }
        $tcpclient.Close()
    }
    if ($success)
    {
        $responseText = "Success: $HostName`:$Port"
    }
    else
    {
        $responseText = "Failed: $HostName`:$Port"
    }
    return $responseText
 }


Test-PortConnection -Host someserver.somedomain.com -Port 22
Test-PortConnection -Host someserver.somedomain.com -Port 80
Test-PortConnection -Host someserver.somedomain.com -Port 1433
Test-PortConnection -Host www.aftonbladet.se -Port 80


