Skip to content

Instantly share code, notes, and snippets.

@lazywinadmin
Created October 1, 2015 04:15
Show Gist options
  • Save lazywinadmin/c60083ce087d0b67e178 to your computer and use it in GitHub Desktop.
Save lazywinadmin/c60083ce087d0b67e178 to your computer and use it in GitHub Desktop.
NetStat -no parsed in PowerShell
function Get-NetStat
{
<#
.SYNOPSIS
This function will get the output of netstat -n and parse the output
.DESCRIPTION
This function will get the output of netstat -n and parse the output
.LINK
http://www.lazywinadmin.com/2014/08/powershell-parse-this-netstatexe.html
.NOTES
Francois-Xavier Cat
www.lazywinadmin.com
@LazyWinAdm
#>
PROCESS
{
# Get the output of netstat
$data = netstat -no
# Keep only the line with the data (we remove the first lines)
$data = $data[4..$data.count]
# Each line need to be splitted and get rid of unnecessary spaces
foreach ($line in $data)
{
# Get rid of the first whitespaces, at the beginning of the line
$line = $line -replace '^\s+', ''
# Split each property on whitespaces block
$line = $line -split '\s+'
# Define the properties
$properties = @{
Protocole = $line[0]
LocalAddressIP = ($line[1] -split ":")[0]
LocalAddressPort = ($line[1] -split ":")[1]
ForeignAddressIP = ($line[2] -split ":")[0]
ForeignAddressPort = ($line[2] -split ":")[1]
State = $line[3]
PID = $line[4]
ProcessName = (Get-Process -id $line[4]).ProcessName
}
# Output the current line
New-Object -TypeName PSObject -Property $properties
}
}
}
Get-NetStat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment