PoshCode Logo PowerShell Code Repository

Get-Netstat 1,0 (modification of post by glnsize view diff)
View followups from Forrest | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/558"></script>download | new post

This will perform a basic netstat.exe command and “objectize” its output.

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.

  1. $null, $null, $null, $null, $netstat = netstat -a -n -o
  2. [regex]$regexTCP = '(?<Protocol>\S+)\s+(?<LocalAddress>\S+)\s+(?<RemoteAddress>\S+)\s+(?<State>\S+)\s+(?<PID>\S+)'
  3. [regex]$regexUDP = '(?<Protocol>\S+)\s+(?<LocalAddress>\S+)\s+(?<RemoteAddress>\S+)\s+(?<PID>\S+)'
  4. foreach ($net in $netstat)
  5. {
  6.     switch -regex ($net.Trim())
  7.     {
  8.         $regexTCP
  9.         {                      
  10.             $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress, State, PID, ProcessName
  11.             $process.Protocol = $matches.Protocol
  12.             $process.LocalAddress = $matches.LocalAddress
  13.             $process.RemoteAddress = $matches.RemoteAddress
  14.             $process.State = $matches.State
  15.             $process.PID = $matches.PID
  16.             $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName
  17.             $process
  18.             continue
  19.         }
  20.         $regexUDP
  21.         {
  22.             $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress, State, PID, ProcessName
  23.             $process.Protocol = $matches.Protocol
  24.             $process.LocalAddress = $matches.LocalAddress
  25.             $process.PID = $matches.PID
  26.            $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName
  27.             $process
  28.             continue
  29.         }
  30.     }
  31. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me