PoshCode Archive  Artifact [b680181499]

Artifact b680181499c8ed343b6d150bf108420ec076b2b5bbdda681da3a8964a49a178d:

  • File Get-Netstat-1-0.ps1 — part of check-in [136844f707] at 2018-06-10 13:57:24 on branch trunk — This will perform a basic netstat.exe command and “objectize” its output. (user: glnsize size: 2015)

# encoding: ascii
# api: powershell
# title: Get-Netstat 1,0
# description: This will perform a basic netstat.exe command and “objectize” its output.  
# version: 0.1
# author: glnsize
# license: CC0
# x-poshcode-id: 558
# x-archived: 2008-09-19T16:44:00
#
# v0.9	Initial Build
# V1.0	Added support for UDP, and processname
# TODO: – break out local and remote ports, e.g. “what’s listening on port 80?” – add ProcessName parameter to filter by said process name. “get-netstat -proc svchost” – add State param.  “get-netstat -state established” – maybe look at the other netstat options…altho that’s bound to introduce a ton more regex variants which would be a PITA.
#
$null, $null, $null, $null, $netstat = netstat -a -n -o
[regex]$regexTCP = '(?<Protocol>\S+)\s+(?<LocalAddress>\S+)\s+(?<RemoteAddress>\S+)\s+(?<State>\S+)\s+(?<PID>\S+)'
[regex]$regexUDP = '(?<Protocol>\S+)\s+(?<LocalAddress>\S+)\s+(?<RemoteAddress>\S+)\s+(?<PID>\S+)'
foreach ($net in $netstat)
{
    switch -regex ($net.Trim())
    {
        $regexTCP
        {			
            $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress, State, PID, ProcessName
            $process.Protocol = $matches.Protocol
            $process.LocalAddress = $matches.LocalAddress
            $process.RemoteAddress = $matches.RemoteAddress
            $process.State = $matches.State
            $process.PID = $matches.PID
            $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName
            $process
            continue
        }
        $regexUDP
        {
            $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress, State, PID, ProcessName
            $process.Protocol = $matches.Protocol
            $process.LocalAddress = $matches.LocalAddress
            $process.PID = $matches.PID
	   $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName
            $process
            continue
        }
    }
}