Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Get-NetStat
- {
- PARAM
- (
- [validateset(
- "Active"
- , "All"
- )]
- [string]$state = "Active"
- )
- $net = netstat "-no"
- $Properties = [regex]::Replace(($net | select -Index 3).trim(),"\s{2,}",";").split(";")
- $netstat = New-Object -TypeName 'System.Collections.Generic.List[pscustomobject]'
- foreach ($line in $net | where {$_ -match 'tcp' -or $_ -match 'udp'})
- {
- $Netstat_Property_Values = $line.Trim().split("") | where {$_ -ne ""}
- $obj = New-Object -TypeName PsCustomObject
- for ($i = 0; $i -lt $Netstat_Property_Values.count; $i++)
- {
- if ($Properties[$i] -match 'address')
- {
- $ip = $Netstat_Property_Values[$i].split(":")
- $ip = $ip[0..$($ip.length - 2)] -join ":"
- try{
- [System.Net.IPAddress]$ip1 = $ip
- } catch {$ip1 = "no"}
- if ($ip1.AddressFamily -eq 'InterNetworkV6')
- {
- $ipfamily = "IPv6"
- }
- elseif ($ip1.AddressFamily -eq 'InterNetwork')
- {
- $ipfamily = "IPv4"
- }
- else
- {
- $ipfamily = "N/A"
- }
- [int]$Port = $Netstat_Property_Values[$i].split(":")[-1]
- [ipaddress]$ipa = $ip
- $obj | Add-Member -MemberType NoteProperty -Name $Properties[$i] -Value $ipa
- $obj | Add-Member -MemberType NoteProperty -Name "$($Properties[$i].split(" ")[0][0])Type" -Value $ipfamily
- $obj | Add-Member -MemberType NoteProperty -Name "$($Properties[$i].split(" ")[0][0])Port" -Value $port
- }
- elseif ($Properties[$i] -match 'pid')
- {
- $obj | Add-Member -MemberType NoteProperty -Name $Properties[$i] -Value $Netstat_Property_Values[$i]
- $obj | Add-Member -MemberType NoteProperty -Name "Process" -Value "$((get-process | where {$_.Id -eq $obj.PID}).Name)"
- }
- else
- {
- $obj | Add-Member -MemberType NoteProperty -Name $Properties[$i] -Value $Netstat_Property_Values[$i]
- }
- }
- $netstat.Add($obj)
- }
- switch ($state)
- {
- "All"
- {
- return $netstat
- break;
- }
- "Active"
- {
- return ($netstat | where {$_.pid -ne 0})
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement