Last active
September 22, 2016 08:20
-
-
Save vScripter/add54f2af5c16c1f1d56 to your computer and use it in GitHub Desktop.
Get-NetStat PowerShell Function
This file contains 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
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. | |
Credit goes to PowerShell MVP Francois-Xavier Cat, who wrote the orignial function to parse the output of netstat.exe -n. | |
I added the ability to query info from a remote system via Invoke-Command (requires that PowerShell remoting be enabled on | |
the destination system), and then use the same functionality in the original script to parse the output. | |
.PARAMETER ComputerName | |
Name of remote system to query | |
.LINK | |
http://www.lazywinadmin.com/2014/08/powershell-parse-this-netstatexe.html | |
.LINK | |
www.github.com/vN3rd | |
#> | |
[cmdletbinding()] | |
param ( | |
[parameter(Mandatory = $false, | |
Position = 0, | |
ValueFromPipeline = $true, | |
ValueFromPipelineByPropertyName = $true)] | |
[ValidateScript({ Test-Connection -ComputerName $_ -Count 2 -Quiet })] | |
[string]$ComputerName = 'localhost' | |
) | |
BEGIN | |
{ | |
if ($ComputerName -eq 'localhost') | |
{ | |
$NetStat = netstat.exe -n | |
} else | |
{ | |
$NetStat = Invoke-Command -ComputerName $ComputerName -ScriptBlock { netstat.exe -n } | |
}# end if/else | |
}# end BEGIN | |
PROCESS | |
{ | |
# Keep only the line with the data (we remove the first lines) | |
$NetStat = $NetStat[4..$NetStat.count] | |
# Each line need to be splitted and get rid of unnecessary spaces | |
foreach ($line in $NetStat) | |
{ | |
# 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] | |
} | |
# Output the current line | |
New-Object -TypeName PSObject -Property $properties | |
}# end foreach | |
}# end PROCESS | |
}# end function Get-NetStat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment