Thursday, May 26, 2011

Shay Levy did an excellent PowerShellization of ‘netstat’ (link) on his blog back in February. JRich also had an excellent take on implementing NetStat in PowerShell (link). There is also a simple one-liner [net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpConnections() that will get you Tcp connection information without the process information but IMHO the info provided is practically useless in most real world scenarios without the process info.

One can argue over which solution is more PowerShellicous, “inlining c#” or “scraping cmd output”. Meanwhile while that flame war is happening I’ll be over here extending either of these solutions because PowerShell is awesome like that. Here I added filtering to the Shay’s solution. Behold:

PS C:\Users\ben> Get-NetworkStatistics skype | ft -AutoSize

Protocol LocalAddress LocalPort RemoteAddress RemotePort State     ProcessName PID 
-------- ------------ --------- ------------- ---------- -----     ----------- --- 
TCP      0.0.0.0      443       0.0.0.0       0          LISTENING Skype       4068
TCP      0.0.0.0      9841      0.0.0.0       0          LISTENING Skype       4068

PS C:\Users\ben> Get-NetworkStatistics -ProcessId 3368


Protocol      : TCP
LocalAddress  : 192.168.10.115
LocalPort     : 49899
RemoteAddress : 204.152.18.196
RemotePort    : 443
State         : ESTABLISHED
ProcessName   : chrome
PID           : 3368

Here’s the source:

Notes