PoshCode Archive  Artifact [f46f6b8c13]

Artifact f46f6b8c138e63644278c63a2dadf77b9317e62b14ac4eac078b6265bab5575f:

  • File Test-TCPPort.ps1 — part of check-in [599a256c74] at 2018-06-10 14:12:03 on branch trunk — - NOTES (user: ChristopheCREMON size: 1371)

# encoding: ascii
# api: powershell
# title: Test-TCPPort
# description: - NOTES
# version: 0.1
# type: function
# author: ChristopheCREMON
# license: CC0
# function: Test-TCPPort
# x-poshcode-id: 6279
# x-derived-from-id: 6280
# x-archived: 2016-07-30T12:14:33
# x-published: 2016-04-05T06:49:00
#
# Author : Christophe CREMON (uxone) – http://powershell.codeplex.com
# Requires : PowerShell V2
# Test if a TCP Port is open or not.
# - EndPoint can be a hostname or an IP address
# - EXAMPLE
# Test-TCPPort -EndPoint server1 -Port 80 
# Return true if port is open, false otherwise
#
# http://powershell.codeplex.com

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
	}
}