PoshCode Archive  Artifact [59f88a6730]

Artifact 59f88a6730873e401c2f36e50d965ce6372ce4c060d6595a1e2bc1be54036b09:

  • File Test-TCPPort.ps1 — part of check-in [f98a699723] at 2018-06-10 13:45:19 on branch trunk — - NOTES (user: ChristopheCREMON size: 1344)

# encoding: ascii
# api: powershell
# title: Test-TCPPort
# description: - NOTES
# version: 0.1
# type: function
# author: ChristopheCREMON
# license: CC0
# function: Test-TCPPort
# x-poshcode-id: 4743
# x-archived: 2015-05-06T13:00:34
# x-published: 2015-12-27T12:20: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
	}
}