PowerShell – Checking whether a TCP port is open using PowerShell

Sometimes when working with customers you need to validate if a particular port has been opened on their Firewall. I am unable to count how many times I’ve had a discussion where a port hasnt been opened. So for simplicity the following PowerShell function allows you to check instantly;

Function Get-CheckPort{
[cmdletbinding()]
Param (
[parameter(Mandatory=$true)]
[string]$ipaddress,
[string]$port
)
# End of Parameters
Process{
  $Date = Get-Date
  $MyDate =  " " + $Date.Day + "." + $Date.Month + "." + $Date.Year + " " + $date.Hour + ":" + $date.Minute
  
  Try{
     $connection = $null
     $connection = New-Object System.Net.Sockets.TcpClient($ipaddress, $port)
  }

  Catch{
       Write-host "Warning: Port $port is closed - $MyDate" -ForegroundColor Red
     }
  if ($connection.Connected){
     Write-Host "Info: Port $port is open - $MyDate" -ForegroundColor Green
    }
   }
 }
Get-CheckPort -ipaddress '' -port ''

As you can see from the test above, I am to validate that port 80 to the teams.microsoft.com is open

Regards
The Author – Blogabout.Cloud

Leave a Reply

Your email address will not be published. Required fields are marked *