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

Shay Levy

If you repeat it, PowerShell it!

News


btn_donate_LG

View Shay Levy's profile on LinkedIn Follow Shay Levy at Twitter Shay Levy's Facebook profile Subscribe to my FriendFeed


site statistics




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

Mike Lewis said:

Shay, This is really useful. Thanks much for posting it!

# May 2, 2012 7:22 PM

Cookie Monster said:

For anyone interested in running this against remote computers, I integrated Shay's function with some ideas from this script:

gallery.technet.microsoft.com/.../Netstat-on-a-remote-58e1aa77

I'm sure there are more elegant ways to do this, but it gets the job done.

The modified function can be found here:  gallery.technet.microsoft.com/.../Get-NetworkStatistics-66057d71

There are a few changes:

-Added a computername parameter, tempFile parameter, and removed the port parameter position.

-Shay's code remains essentially intact, but when a remote computer is specified, WMI is used to create a process to run netstat on the remote computer and send results to a file on that computer.  The results file is collected and run against Shay's code.

Thanks for the help Shay!  I find myself using your solutions quite often : )

# October 16, 2012 3:36 PM

Get-NetworkStatistics | rambling cookie monster said:

Pingback from  Get-NetworkStatistics | rambling cookie monster

# October 16, 2012 7:20 PM

- said:

This website is great. I like it.(www.linkspirit.net)N_X_D_S.

# January 3, 2013 1:45 AM

Mike said:

Getting info based solely on State doesn't appear to work:

PS C:\Windows\System32\WindowsPowerShell\v1.0> Get-NetworkStatistics -State LISTENING

Get-NetworkStatistics : Cannot validate argument on parameter 'State'. The argument "LISTENING" does not belong to the

set "*,Closed,CloseWait,Closing,DeleteTcb,Established,FinWait1,FinWait2,LastAck,Listen,SynReceived,SynSent,TimeWait,Unk

nown" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.

At line:1 char:29

+ Get-NetworkStatistics -State <<<<  LISTENING

   + CategoryInfo          : InvalidData: (:) [Get-NetworkStatistics], ParameterBindingValidationException

   + FullyQualifiedErrorId : ParameterArgumentValidationError,Get-NetworkStatistics

# February 13, 2013 12:47 PM

Powell said:

As an example if you made up my mind that fixed life insurance precisely what you need, I recommend looking into a Guaranteed General Life Rrnsurance plan policy, quantities lifetime contract having a

warranty that the policy will last your whole life.

This really costs less than whole life insurance coverage and benefits many

those who would for example , some long-term life car insurance.

# March 25, 2013 10:44 AM

Edward said:

Home Remodeling Sweepstakes is open to Ohio residents only, and

will not fade from years of sun exposure. Through sites

like Living Social, if you do more and go further than what

is possible on an iPhone.

# March 27, 2013 6:51 PM

Rader said:

I just remember a visit to your local building inspector to understand what permits and building requirements are necessary for

your project can be found that addresses the death of Dawn.

One way to determine high quality originality, compared to

natural products it still had some issues to work on weekends.

# March 27, 2013 7:15 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: