# encoding: ascii
# api: powershell
# title: Test-TCPPort
# description: Test-TCPPort
# version: 0.1
# type: function
# author: Test-TCPPort
# license: CC0
# function: Test-TCPPort
# x-poshcode-id: 6329
# x-archived: 2016-06-03T00:08:45
# x-published: 2016-04-29T11:21:00
#
#
function Test-TCPPort
{
    [CmdletBinding()]
    param
    (
        [Parameter(Position=0,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('hostname')]
        [Alias('cn')]
        [string[]]$Name = $env:COMPUTERNAME,

        [Parameter(Position=2)]
        [int]$Port=80,

        [Parameter(Position=3)]
        [Int]$TimeOut = 1000
    )

    BEGIN { 
	    $Socket = New-Object System.Net.Sockets.TCPClient
    }

    PROCESS
    {
        $Connect = $Socket.BeginConnect($Name,$Port,$null,$null)
	    if ( $Connect.IsCompleted )
	    {
	    	$Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut,$false)
	    	if(!$Wait) 
	    	{
	    		return $false 
	    	} 
	    	else
	    	{
	    		$Socket.EndConnect($Connect)
	    		return $true
	    	}
	    }
	    else
	    {
	    	return $false
	    }
        }

    END { 
        $Socket.Close()
    }
}
