0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Check if Port is Open

Use Test-NetConnection -ComputerName 'hostname' -Port portnumber in PowerShell to check if a port is open; it returns connection status and details.
📋

Examples

InputTest-NetConnection -ComputerName 'localhost' -Port 80
OutputComputerName : localhost RemoteAddress : ::1 RemotePort : 80 InterfaceAlias : Loopback Pseudo-Interface 1 SourceAddress : ::1 TcpTestSucceeded : True
InputTest-NetConnection -ComputerName 'google.com' -Port 443
OutputComputerName : google.com RemoteAddress : 142.250.190.78 RemotePort : 443 InterfaceAlias : Ethernet SourceAddress : 192.168.1.100 TcpTestSucceeded : True
InputTest-NetConnection -ComputerName 'example.com' -Port 9999
OutputComputerName : example.com RemoteAddress : 93.184.216.34 RemotePort : 9999 InterfaceAlias : Ethernet SourceAddress : 192.168.1.100 TcpTestSucceeded : False
🧠

How to Think About It

To check if a port is open, you try to connect to that port on the target computer. If the connection succeeds, the port is open; if it fails, the port is closed or blocked. PowerShell's Test-NetConnection command does this by attempting a TCP connection and reporting the result.
📐

Algorithm

1
Get the target computer name or IP address.
2
Get the port number to check.
3
Attempt a TCP connection to the target computer on the given port.
4
Check if the connection was successful.
5
Return the connection status (open or closed).
💻

Code

powershell
param(
    [string]$ComputerName = 'localhost',
    [int]$Port = 80
)

$result = Test-NetConnection -ComputerName $ComputerName -Port $Port
if ($result.TcpTestSucceeded) {
    Write-Output "Port $Port on $ComputerName is open."
} else {
    Write-Output "Port $Port on $ComputerName is closed or unreachable."
}
Output
Port 80 on localhost is open.
🔍

Dry Run

Let's trace checking port 80 on localhost through the code

1

Set parameters

$ComputerName = 'localhost', $Port = 80

2

Run Test-NetConnection

Test-NetConnection tries to connect to localhost on port 80

3

Check result

$result.TcpTestSucceeded is True

4

Output message

Print 'Port 80 on localhost is open.'

StepActionValue
1Parameterslocalhost, 80
2Test-NetConnection resultTcpTestSucceeded = True
3OutputPort 80 on localhost is open.
💡

Why This Works

Step 1: Using Test-NetConnection

The Test-NetConnection cmdlet tries to open a TCP connection to the specified computer and port.

Step 2: Checking TcpTestSucceeded

The property TcpTestSucceeded tells if the connection was successful, meaning the port is open.

Step 3: Outputting result

Based on the connection success, the script prints whether the port is open or closed.

🔄

Alternative Approaches

Using System.Net.Sockets.TcpClient
powershell
param(
    [string]$ComputerName = 'localhost',
    [int]$Port = 80
)

$tcpClient = New-Object System.Net.Sockets.TcpClient
try {
    $tcpClient.Connect($ComputerName, $Port)
    Write-Output "Port $Port on $ComputerName is open."
} catch {
    Write-Output "Port $Port on $ComputerName is closed or unreachable."
} finally {
    $tcpClient.Dispose()
}
This method uses .NET classes directly and works on older PowerShell versions but requires manual error handling.
Using Test-Connection with Port Check (Legacy)
powershell
param(
    [string]$ComputerName = 'localhost',
    [int]$Port = 80
)

if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
    $socket = New-Object System.Net.Sockets.TcpClient
    try {
        $socket.Connect($ComputerName, $Port)
        Write-Output "Port $Port on $ComputerName is open."
    } catch {
        Write-Output "Port $Port on $ComputerName is closed or unreachable."
    } finally {
        $socket.Dispose()
    }
} else {
    Write-Output "$ComputerName is unreachable."
}
This older approach first checks if the host is reachable before testing the port, adding extra steps.

Complexity: O(1) time, O(1) space

Time Complexity

The operation is a single network connection attempt, so it runs in constant time regardless of input size.

Space Complexity

The script uses a fixed amount of memory for variables and connection objects, so space is constant.

Which Approach is Fastest?

Using Test-NetConnection is fastest and simplest because it is optimized and built-in; using TcpClient is slightly more manual and verbose.

ApproachTimeSpaceBest For
Test-NetConnectionO(1)O(1)Simple, modern PowerShell scripts
System.Net.Sockets.TcpClientO(1)O(1)Older PowerShell versions or custom handling
Test-Connection + TcpClientO(1)O(1)When host reachability must be confirmed first
💡
Use Test-NetConnection for a simple and reliable port check in PowerShell 4.0 and above.
⚠️
Beginners often forget to specify the port number or use the wrong parameter, causing the test to fail or check the wrong port.