Using PowerShell Version 3, How Do You Determine If a Port Is Open for a given IP Address?

Problem scenario
You are using Windows 7 and PowerShell version 3.  You want to test if a port is open to a given IP address.  (If you are using a modern version of PowerShell, use the Test-NetConnection command.)   How do you find out if a port of an IP address is open or not?

Use the PowerShell function Test-TCPPortConnection written by Jonathan Medd.  Every line of this code except the last line was taken from here.

function Test-TCPPortConnection {
 Test the response of a computer to a specific TCP port

 Test the response of a computer to a specific TCP port

 .PARAMETER  ComputerName
 Name of the computer to test the response for

 TCP Port number(s) to test



 PS C:\> Test-TCPPortConnection -ComputerName Server01

 PS C:\> Get-Content Servers.txt | Test-TCPPortConnection -Port 22,443
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the computer to test",
 [Int[]]$Port = 3389
begin {
 $TCPObject = @()
 process {
 foreach ($Computer in $ComputerName) {
foreach ($TCPPort in $Port) {
 $Connection = New-Object Net.Sockets.TcpClient
 try {
 if ($Connection.Connected) {
$Response = “Open"
 catch [System.Management.Automation.MethodInvocationException]
 $Response = “Closed / Filtered"
 $Connection = $null
 $hash = @{
 ComputerName = $Computer
 Port = $TCPPort
 Response = $Response
 $Object = New-Object PSObject -Property $hash
 $TCPObject += $Object
end {
Write-Output $TCPObject
Test-TCPPortConnection -ComputerName x.x.x.x -Port 80  # End of code

Replace x.x.x.x with the IP address you want to test.  Replace 80 with the given port you want to test.  You do not have to save the file to run it in the PowerShell ISE application.  Run the code and examine the results.  You will see if a given port is open or not (closed or filtered).

Leave a comment

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