PoshCode Archive  Artifact [e530aefb33]

Artifact e530aefb3342aacc78c6eb8a5883afea3ab0cd1ed514c4b02343b6cd69052227:

  • File Test-TCPPort.ps1 — part of check-in [03c3c7ad66] at 2018-06-10 13:19:41 on branch trunk — - NOTES (user: Andy Arismendi size: 1510)

# encoding: ascii
# api: powershell
# title: Test-TCPPort
# description: - NOTES
# version: 0.1
# type: function
# author: Andy Arismendi
# license: CC0
# function: Test-TCPPort
# x-poshcode-id: 3058
# x-archived: 2015-01-24T06:34:30
# x-published: 2012-11-20T13:55: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 -ComputerName server1 -Port 80 
# Return true if port is open, false otherwise
# - Revision History:
# 2011-11-20: Andy Arismendi – Added error handling, forcing use of IP v4 so the IPAddress parse method doesn’t bomb.
#
function Test-TCPPort {
	param (
		[parameter(Mandatory=$true)]
		[string] $ComputerName,
		
		[parameter(Mandatory=$true)]
		[string] $Port
	)
	
	try {
		$TimeOut = 5000
		$IsConnected = $false
		$Addresses = [System.Net.Dns]::GetHostAddresses($ComputerName) | ? {$_.AddressFamily -eq 'InterNetwork'}
		$Address = [System.Net.IPAddress]::Parse($Addresses)
		$Socket = New-Object System.Net.Sockets.TCPClient
		
		$Connect = $Socket.BeginConnect($Address, $Port, $null, $null)
		$Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut, $false)	
		
		if ( $Socket.Connected ) {
			$IsConnected = $true
			$Socket.Close()
		} else {
			$IsConnected = $false
		}
		
	} catch {
		Write-Debug $_
		$IsConnected = $false
	} finally {
		return $IsConnected
	}
}