Created
September 15, 2011 20:03
-
-
Save slacker/1220314 to your computer and use it in GitHub Desktop.
Netstat Powershell Wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on code found at http://poshcode.org/2694 | |
$null, $null, $null, $null, $netstat = netstat -ano | |
$ps = Get-Process | |
[regex]$regexTCP = '(?<Protocol>\S+)\s+(?<LAddress>\S+):(?<LPort>\S+)\s+(?<RAddress>\S+):(?<RPort>\S+)\s+(?<State>\S+)\s+(?<PID>\S+)' | |
[regex]$regexUDP = '(?<Protocol>\S+)\s+(?<LAddress>\S+):(?<LPort>\S+)\s+(?<RAddress>\S+):(?<RPort>\S+)\s+(?<PID>\S+)' | |
$return = @() | |
foreach ($line in $netstat) | |
{ | |
switch -regex ($line.Trim()) | |
{ | |
$regexTCP | |
{ | |
$process = New-Object psobject -property @{ | |
Protocol = $matches.Protocol | |
LocalAddress = $matches.LAddress | |
LocalPort = $matches.LPort | |
RemoteAddress = $matches.RAddress | |
Remoteport = $matches.RPort | |
State = $matches.State | |
ID = [int]$matches.PID | |
ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName | |
} | |
$return = $return + $process | |
continue | |
} | |
$regexUDP | |
{ | |
$process = New-Object psobject -property @{ | |
Protocol = $matches.Protocol | |
LocalAddress = $matches.LAddress | |
LocalPort = $matches.LPort | |
RemoteAddress = $matches.RAddress | |
Remoteport = $matches.RPort | |
State = $matches.State | |
ID = [int]$matches.PID | |
ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName | |
} | |
$return = $return + $process | |
continue | |
} | |
} | |
} | |
$return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment