Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2011/02/how-to-find-running-processes-and-their #278

Open
utterances-bot opened this issue Oct 5, 2022 · 3 comments
Open

2011/02/how-to-find-running-processes-and-their #278

utterances-bot opened this issue Oct 5, 2022 · 3 comments

Comments

@utterances-bot
Copy link

PowerShell - How to find running processes and their port number - LazyWinAdmin

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.

https://lazywinadmin.github.io/2011/02/how-to-find-running-processes-and-their.html

Copy link

Doesnt work with PowerShell 7.x

What is Select-String-Pattern?

Copy link

Few spaces missing, such as "Select-String -Pattern", "New-Object PSObject", "Get-Process -Id" and "Select-Object -Property" but other than that great wee script, gives me exactly what I need.
Thank you!

Copy link

Working script with spaces removed:

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
 }
 }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants