First I just want to make sure user Erik Bitemo gets credit for the original code I'm using here. The output is what I'm looking for with one exception: One of the ports disappears and "System System5" show up in its place and I can't figure out why it's happening.
Goal: Show all TCP (Listening) and UDP ports and the process associated with each on same line.
One liner being used:
$nets = netstat -bano|select-string 'LISTENING|UDP'; foreach ($n in $nets) { $p = $n -replace ' +',' '; $nar = $p.Split(' '); $pname = $(Get-Process -id $nar[-1]).ProcessName; $n -replace "$($nar[-1])","$($ppath) $($pname)"; }
Example Output:
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING svchost
TCP 0.0.0.0: System System5 0.0.0.0:0 LISTENING System
TCP 0.0.0.0:623 0.0.0.0:0 LISTENING LMS
The port that it changes is 445 but I have no idea why it's changing only that one when the rest of the ports are working as intended. Why is the script changing 445 to "System System5"?
Using other tools is unfortunately not possible so I'm limited to using built-in Windows tools.
Answer
$p
could be something like TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
and $nar[-1]
is string 4
so -replace
operator takes all 4
s:
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
↑↑ ↑
Force replacing only last occurrence of $nar[-1]
using end of line anchor (escaped $
):
$p -replace "$($nar[-1])`$","$ppath $pname"
Read as well Matt's answer to Replacing last occurrence of substring in string at stackoverflow.
BTW:
$ppath
is not defined…- …and
netstat -ano
should suffice (note that-b
option can be time-consuming and will fail unless you have sufficient permissions).
Comments
Post a Comment