Finding Ports with Netstat and PowerShell

Adam Bertram

Read more posts by this author.

Are you using netstat to find open ports? Output a bit too clunky for you? Read on!

I recently had a request from a coworker that seemed to be innocent enough. He simply needed a “PowerShell netstat”. I’ve been known to throw down some regex from time to time so I was up the for the challenge and didn’t think too much of it….until I dove in.

As usual, I severely underestimated the time it would take! The basic premise of this little project is to figure out some kind of structure that netstat outputs ports. Even though it’s a big ol’ string there’s always some kind of common form that it uses. It turns out discovering this was extremely difficult with netstat.

Why? Because sometimes a port in netstat had the associated process owner, sometimes a port had an associated service, each port could either be IPv4 or IPv6 which had a very different string format and on top of that, the hardest part was the process owner and service for a port were not on the same line.

Introducing Get-LocalPort.ps1! This script (or function) allows you to run netstat -anb , finds ports and gets the output in PowerShell objects rather than text.

Related: PowerShell Function Introduction

What does this mean to you? You are now able to do things like Get-LocalPort.ps1 | Where-Object {$.ProcessOwner -eq 'svchost.exe'} to get all ports that are open by a process or Get-LocalPort.ps1 | Where-Object {$.State -eq 'LISTENING'} to find all of the ports that are in a listening state.

P.S. The PowerShell team has sensed many IT pros’ pain and came out with Convert-FromString in PowerShell v5. I chose not to pursue this because this will be running in production and I have rule to never run non-RTM code in production and since it’s only PSv5 I have many machines that are still v4 that I’ll need to run this on.

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!