PoshCode Archive  Artifact [e81dcbf42f]

Artifact e81dcbf42f04b74976ef5284dbe20a2ea8c0bf93ddb42045ec584d391d5cdfdb:

  • File Get-Netstat-1-2.ps1 — part of check-in [2ac864da20] at 2018-06-10 13:09:37 on branch trunk — This will perform a basic netstat.exe command and “objectize” its output. (user: glnsize size: 2673)

# encoding: ascii
# api: powershell
# title: Get-Netstat 1,2
# description: This will perform a basic netstat.exe command and “objectize” its output.  
# version: 0.1
# author: glnsize
# license: CC0
# x-poshcode-id: 2398
# x-derived-from-id: 2694
# x-archived: 2016-05-28T14:27:06
# x-published: 2011-12-04T17:49: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
#
$null, $null, $null, $null, $netstat = netstat -a -n -o
$ps = Get-Process
[regex]$regexTCP = '(?<Protocol>\S+)\s+((?<LAddress>(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?<LAddress>\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?<Lport>\d+)\s+((?<Raddress>(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?<RAddress>\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?<RPort>\d+)\s+(?<State>\w+)\s+(?<PID>\d+$)'

[regex]$regexUDP = '(?<Protocol>\S+)\s+((?<LAddress>(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?<LAddress>\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?<Lport>\d+)\s+(?<RAddress>\*)\:(?<RPort>\*)\s+(?<PID>\d+)'

[psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName

foreach ($net in $netstat)
{
    switch -regex ($net.Trim())
    {
        $regexTCP
        {          
            $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
        }
        $regexUDP
        {          
            $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 | ? {$_.Id -eq $matches.PID} ).ProcessName
        }
    }
$process
}