PoshCode Archive  Artifact [9cae7381b7]

Artifact 9cae7381b7e155e12c0eca6aa16aa37b8007d21275a3c6963949e55713b544be:

  • File Test-TCPPort.ps1 — part of check-in [c7ea2c0947] at 2018-06-10 14:13:18 on branch trunk — Test-TCPPort (user: Test-TCPPort size: 1262)

# 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()
    }
}