Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kiwimato/c211c07cd906d9ea17e9948dfa51b8f3 to your computer and use it in GitHub Desktop.
Save kiwimato/c211c07cd906d9ea17e9948dfa51b8f3 to your computer and use it in GitHub Desktop.
Get-NetworkStatistics.ps1
function Get-NetworkStatistics
{
$properties = 'Protocol','LocalAddress','LocalPort'
$properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'
netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {
$item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::')
{
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else
{
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else
{
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
New-Object PSObject -Property @{
PID = $item[-1]
ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
Protocol = $item[0]
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
} |Select-Object -Property $properties
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment