Wednesday, February 19, 2014

PowerShell: Netstat Established Connections List

This is a script which you can adapt to your needs.  I wanted to find the "Established" foreign computers and the programs which are talking to them.  PowerShell doesn't have a native tool (not that I'm aware of) so most use NetStat.  Here is the script I made that finds the remote host FQDN and converts the Process ID into a program name.  When finished, it displays a table but you can easily out-gridview if you'd like.

$Netstats = netstat -aof|select-string "active connections","Proto","\[::","Can not obtain" -notmatch|select-string "establish"
$process = get-process|select id,name

foreach($n in $Netstats){
$temp = $n.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
$p = ($process|?{$_.id -like $temp[4]}).Name
$outcsv += write ($temp[2] + "," + $p + "`n")}
$Final = $outcsv|convertfrom-csv -header RemotePort,Program
$Final|ft -autosize

I'm sure you'll find it doesn't fit all your needs but should give you some insight on how to manipulate NetStat's output.

Reference:
Netstat
Get-Networkstatistics