DCSIMG
How to find running processes and their port number - Shay Levy

Shay Levy

If you repeat it, PowerShell it!

How to find running processes and their port number

The netstat command line utility displays protocol statistics and current TCP/IP network connections. If we want to display the associated process identifier (PID) of each process we add the -o parameter.

image

To filter the result we need to pipe to the Find utility and again, the result is text!. In PowerShell we can get the same information with the following command, however the process PID is missing and the connections in LISTENING state are not included by default.

PS > [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpConnections()

With the Get-NetworkStatistics function we can get the same information but each returned connection is an object. Get-NetworkStatistics parses only TCP/UDP connections (entries that starts with '[::' are ignored). Each connection is divided into two columns. For example, if the 'Local Address' column has a value of '0.0.0.0:80' the IP address will be shown in the LocalAddress property (e.g 0.0.0.0)  and the port number in the LocalPort property (e.g 80). The name of each process is also added to the result. This should make filtering much more easier when we pipe the result to the Where-Object cmdlet, allowing us to filter on any property of a connection.

UPDATE1: Added support for IPv6 connections. @xcud and surveyor, thanks for the input!
UPDATE2: Per @xcud request (see comment below) I published an extended version of the function HERE.

 

function Get-NetworkStatistics
{
    $properties = 'Protocol','LocalAddress','LocalPort'
    $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'

    netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {

        $item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)

        if($item[1] -notmatch '^\[::')
        {           
            if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
            {
               $localAddress = $la.IPAddressToString
               $localPort = $item[1].split('\]:')[-1]
            }
            else
            {
                $localAddress = $item[1].split(':')[0]
                $localPort = $item[1].split(':')[-1]
            } 

            if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
            {
               $remoteAddress = $ra.IPAddressToString
               $remotePort = $item[2].split('\]:')[-1]
            }
            else
            {
               $remoteAddress = $item[2].split(':')[0]
               $remotePort = $item[2].split(':')[-1]
            } 

            New-Object PSObject -Property @{
                PID = $item[-1]
                ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
                Protocol = $item[0]
                LocalAddress = $localAddress
                LocalPort = $localPort
                RemoteAddress =$remoteAddress
                RemotePort = $remotePort
                State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
            } | Select-Object -Property $properties
        }
    }
}

Get-NetworkStatistics | Format-Table
image

To get all processes running on a local port 80:

image

Or find a connection information by filtering on ProcessName:

image

Comments

Twitter Trackbacks for How to find running processes and their port number - Shay Levy [microsoft.co.il] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 How to find running processes and their port number - Shay Levy         [microsoft.co.il]        on Topsy.com

# February 10, 2011 5:45 PM

OldDog said:

Great post and very timley, for me.

I need to be able to check two Ports on a server to make sure that they are open as opart of troubleshooting OpsWare (HPSA). They are ports 1002 and 3001.

I ran you function and got this:

Protocol     LocalAddress LocalPort    RemoteAddres RemotePort  State

                                      s

--------     ------------ ---------    ------------ ----------  -----

TCP          0.0.0.0      1002         0.0.0.0      0           LISTENING

Port 3001 returned nothing.

Should I assume that it is closed or is it just not active?

In any event thanks for this.

# February 10, 2011 5:47 PM

ScriptFanatic said:

It could be that at the time you ran the command there was no process listening to port 3001 or that it's not active. You can also use another method to check if a port is open on a target machine, check the Test-TcpPort function here:

halr9000.com/.../418

# February 10, 2011 6:00 PM

surveyor said:

It does not work for adapters with IPV6-addresses. Maybe a regex-filter would be more flexible than the splits?

TCP             [fe80           50219           [fe80           3587            HERGESTELLT     svchost         1132

# February 10, 2011 11:16 PM

Powershell: How to find running processes and their port number « MS Tech BLOG said:

Pingback from  Powershell: How to find running processes and their port number « MS Tech BLOG

# February 11, 2011 12:25 AM

Powershell: How to find running processes and their port number « MS Tech BLOG said:

Pingback from  Powershell: How to find running processes and their port number « MS Tech BLOG

# February 11, 2011 12:25 AM

ScriptFanatic said:

surveyor, I updated the function and added support for IPv6.

# February 11, 2011 9:30 AM

Episode 139 – Brian and Ben from DevFarm « PowerScripting Podcast said:

Pingback from  Episode 139 – Brian and Ben from DevFarm «  PowerScripting Podcast

# February 15, 2011 5:39 AM

xcud said:

This is one of my favorite powershell functions of late. FWIW, this would even more useful if it took parameter input; i.e. processname (with wildcard support), address, or port

Usage:

Get-NetworkStatistics -ProcessName skype

Get-NetworkStatistics -Address 192.168.1.1

Get-NetworkStatistics -Port 80

Maybe with a default to ProcessName:

Get-NetworkStatistics skype

# March 2, 2011 12:09 AM

Richard Siddaway's Blog said:

The last part of the puzzle is to deal with netstat.   netstat -an $computer = "localhost"

# July 4, 2011 9:30 PM

Computer Report V: netstat | Richard Siddaway's Blog said:

Pingback from  Computer Report V: netstat | Richard Siddaway's Blog

# July 4, 2011 9:31 PM

redcode said:

when i try to run your function, it does not works.. :(

i am tring in administrator powershell...

for example...

ps c:\swsetup> .\Get-NetworkStatistics -ProcessName *md - Protocol tcp

it does anything...

??

ps c:\swsetup>Get-NetworkStatistics -ProcessName *md - Protocol tcp

it is same

# December 20, 2011 12:28 PM

ScriptFanatic said:

If you saved the function in a script file then you need to dot-source the file first (loads the function into memory) and then you can execute it:

# dot source the script file

PS> . c:\Get-NetworkStatistics.ps1

# call the function

PS > Get-NetworkStatistics -ProcessName *md - Protocol tcp

# December 20, 2011 1:48 PM

KW said:

How can I run this against a remote computer?

# January 5, 2012 12:30 AM

ScriptFanatic said:

You can't. netstat works only locally and doesn't support remote computers. However, if you have PowerShell Remoting enabled on the target computer then you can use Invoke-Command cmdlet to execute it on the remote machine.

# January 5, 2012 10:05 AM

Le init.ps1 de ma PowerCLI » vg5000.org said:

Pingback from  Le init.ps1 de ma PowerCLI  » vg5000.org

# January 9, 2012 12:13 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: