Testing for open ports with PowerShell

Want to find out if a TCP port is open via a firewall and/or if something is listening on that port? From within a script? You can use PowerShell.

A colleague found this, which uses System.Net.Sockets.TcpClient from the .NET framework via PowerShell. That would work, but then I found Test-NetConnection.

Test-NetConnection allows testing of TCP ports, and is a built-in cmdlet, which for me is preferable over custom code wherever possible. I’d previously used Test-Connection, which is simpler and just uses ICMP echo requests (aka ping).

I’m using the cmdlet as follows:

if(Test-NetConnection -ComputerName 192.168.1.51 -Port 443 -InformationLevel Quiet){
    # Something is listening on that port, do some stuff
} else {
    # Nothing listening on that port, do something else
}

Simple as that.

This entry was posted in Networking, PowerShell and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s