PoshCode Archive  Artifact [183ea988ad]

Artifact 183ea988ad7bf2c7dbc7a3f6b6f769de6b0ae027f90200c8b1a8ec66088bbb01:

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

# encoding: ascii
# api: powershell
# title: Test-TCPPort
# description: - NOTES
# version: 0.1
# type: function
# author: ChristopheCREMON
# license: CC0
# function: Test-TCPPort
# x-poshcode-id: 3055
# x-derived-from-id: 3058
# x-archived: 2011-12-10T21:06:11
# x-published: 2011-11-20T13:35:00
#
# Author : Christophe CREMON (uxone) – http://powershell.codeplex.com
# Requires : PowerShell V2
# -Revision History:
# 2011-11-20: Andy Arismendi – Added error handling, forcing use of IP v4 so the IPAddress parse method doesn’t bomb.
# 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
#
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
		} else {
			$IsConnected = $false
		}
		
	} catch {
		Write-Warning $_
		$IsConnected = $false
	} finally {
		$Socket.Close()
		return $IsConnected
	}
}