From time to time it is necessary to check if specific TCP ports are open on remote servers. If you have many servers to check it can be a hassle to use telnet or other tools and check each server one by one. It is also often useful in other scripts to test if a remote server/port is alive before running code on them. To accomplish this I have written this little function.
function Test-PortAlive {
#############################################################################################
##Function: Test-PortAlive
##
##Description: Tests connection on a given server on a given port.
##
##Created by: Noam Wajnman
##Creation Date: April 02, 2014
##############################################################################################
[CmdletBinding()]
[OutputType([System.boolean])]
param(
[Parameter(ValueFromPipeline=$true)][System.String[]]$server,
[int]$port
)
$socket = new-object Net.Sockets.TcpClient
$connect = $socket.BeginConnect($server, $port, $null, $null)
$NoTimeOut = $connect.AsyncWaitHandle.WaitOne(500, $false)
if ($NoTimeOut) {
$socket.EndConnect($connect) | Out-Null
return $true
}
else {
return $false
}
}
The function takes two parameters $server and $port. $server is the name of the remote server to test and $port is the number of the TCP port to check the status of. The $server parameter can even be passed via the pipeline making it very easy to run. The function returns either $true or $false depending on whether the port is open or not. To avoid long wait times due to closed ports I have included a relatively short timeout value of 500 ms before the result is determined.
I have included a few examples below of how to call the function.
1. Normal
Test-PortAlive -port 135 "some_server"
Here I just run the function as normal and pass both params. I chose port 135 in this example but it could be any port.
2. Pipeline
$Array_of_Server_Names | Test-PortAlive -port 135
In this example I am using an array to pass the server names to the function via the pipeline. I again chose port 135 in this example.
That’s it. I hope you find this function useful. Enjoy!!