# encoding: ascii
# api: powershell
# title: Get-Netstat 1,3
# description: This will perform a basic netstat.exe command and “objectize” its output.
# version: 0.1
# author: Ivan F
# license: CC0
# x-poshcode-id: 2694
# x-archived: 2016-06-20T00:32:03
# x-published: 2011-05-25T15:59:00
#
# v0.9 Initial Build – Hal
# V1.0 Added support for UDP, and processname -Glenn
# v1.1 Expanded [regex] statements to encompass IPV4/IPV6/ports. -Glenn
# v1.2 Changed the process name lookup to make script a bit faster -Ivan
# v1.3 Simplified RegEx to make IPv6 work. Had issues in PowerGUI until $process was initialized in the For loop
#
$null, $null, $null, $null, $netstat = netstat -a -n -o
$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+)'
[psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName
foreach ($net in $netstat)
{
switch -regex ($net.Trim())
{
$regexTCP
{
$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName
$process.Protocol = $matches.Protocol
$process.LocalAddress = $matches.LAddress
$process.Localport = $matches.LPort
$process.RemoteAddress = $matches.RAddress
$process.Remoteport = $matches.RPort
$process.State = $matches.State
$process.PID = $matches.PID
$process.ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName
$process
continue
}
$regexUDP
{
$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName
$process.Protocol = $matches.Protocol
$process.LocalAddress = $matches.LAddress
$process.Localport = $matches.LPort
$process.RemoteAddress = $matches.RAddress
$process.Remoteport = $matches.RPort
$process.State = $matches.State
$process.PID = $matches.PID
$process.ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName
$process
continue
}
}
}