Skip to content

Instantly share code, notes, and snippets.

@slacker
Created September 15, 2011 20:03
Show Gist options
  • Save slacker/1220314 to your computer and use it in GitHub Desktop.
Save slacker/1220314 to your computer and use it in GitHub Desktop.
Netstat Powershell Wrapper
# 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