PowerShell Function – Test Server TCP Ports

Hi Guys,

Here is a PowerShell Function I wrote couple of years ago. The purpose of this PowerShell function was to test if the given TCP ports where opened or not on specified computers.

We needed this kind of function to keep tracks of customer network teams work, which was taking to long to open couple of TCP ports.

[ps]function Test-ServerTCPPort {
???? <#
???? .SYNOPSIS
???? Function to test a list of TCP ports over a list of computers.

???? .PARAMETER ComputerName
???? List of computers to test.

???? .PARAMETER TCPPort
???? List of TCP ports to test.

???? .NOTES
???? Author: Thomas Prud’homme (@prudhomme_wtf)

???? .LINK
???? https://blog.prudhomme.wtf
?????? https://blog.prudhomme.wtf/powershell-function-test-server-tcp-ports/
#>

[CmdletBinding()]
???? Param(
???? ???? [Parameter(
?????? ?????? ???? Mandatory = $true,
?????? ???? ???? HelpMessage = "List of computers to test"
?????? ?????? )]
???? ???? [Alias("Hostname","Ip","Fqdn")]
???? ???? [String[]]$ComputerName,

???? ???? [Parameter(
?????? ?????? ???? Mandatory = $true,
?????? ???? ???? HelpMessage = "List of TCP ports to test"
?????? ?????? )]
???? ???? [String[]]$TCPPort
???? )

???? foreach ($computer in $ComputerName) {
???? ???? if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
???? ???? ???? foreach ($testedPort in $TCPPort) {
???? ???? ???? ???? try {
???? ???? ???? ???? ???? $null = New-Object -TypeName System.Net.Sockets.TCPClient -ArgumentList $computer,$testedPort
???? ???? ???? ???? ???? New-Object -TypeName PSObject -Property @{
???? ???? ???? ???? ???? ???? Server = $computer
???? ???? ???? ???? ???? ???? Port = $testedPort
???? ???? ???? ???? ???? ???? Status = "Opened"
???? ???? ???? ???? ???? }
???? ???? ???? ???? }
???? ???? ???? ???? catch {
???? ???? ???? ???? ???? New-Object -TypeName PSObject -Property @{
???? ???? ???? ???? ???? ???? Server = $computer
???? ???? ???? ???? ???? ???? Port = $testedPort
???? ???? ???? ???? ???? ???? Status = "Unknown"
???? ???? ???? ???? ???? }
???? ???? ???? ???? }
???? ???? ???? }
???? ???? } else {
???? ???? ???? New-Object -TypeName PSObject -Property @{
???? ???? ???? ???? Server = $computer
???? ???? ???? ???? Port = $null
???? ???? ???? ???? Status = "Server did not respond to ping"
???? ???? ???? }
???? ???? }
???? }
}[/ps]

Here is an example of what the function will display as an output:
[ps]PS C:\Users\tph> Test-ServerTCPPort -ComputerName tools.home.lan -TCPPort 80,443,3389

Port Status Server
—- —— ——
80 Opened tools.home.lan
443 Unknown tools.home.lan
3389 Opened tools.home.lan[/ps]