PoshCode Archive  Artifact [2fcf7892c6]

Artifact 2fcf7892c61d3b729f04e3c36684f5c5e0d4f29d72fe2d3a3f648fc3b9dc1b05:

  • File Test-TCPPort.ps1 — part of check-in [b60842531c] at 2018-06-10 14:12:06 on branch trunk — - NOTES (user: siweb02 size: 1335)

# encoding: ascii
# api: powershell
# title: Test-TCPPort
# description: - NOTES
# version: 0.1
# type: function
# author: siweb02
# license: CC0
# function: Test-TCPPort
# x-poshcode-id: 6280
# x-archived: 2016-11-18T00:57:52
# 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
	}
}