PoshCode Logo PowerShell Code Repository

Get-Netstat 1,1 by glnsize 5 years ago
View followups from Ivan F, Richard Vantreas and HansO | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/560"></script>download | new post

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

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

  1. $null, $null, $null, $null, $netstat = netstat -a -n -o
  2. [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+$)'
  3.  
  4. [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+)'
  5.  
  6. [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName
  7.  
  8. foreach ($net in $netstat)
  9. {
  10.     switch -regex ($net.Trim())
  11.     {
  12.         $regexTCP
  13.         {          
  14.             $process.Protocol = $matches.Protocol
  15.             $process.LocalAddress = $matches.LAddress
  16.             $process.Localport = $matches.LPort
  17.             $process.RemoteAddress = $matches.RAddress
  18.             $process.Remoteport = $matches.RPort
  19.             $process.State = $matches.State
  20.             $process.PID = $matches.PID
  21.             $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName
  22.         }
  23.         $regexUDP
  24.         {          
  25.             $process.Protocol = $matches.Protocol
  26.             $process.LocalAddress = $matches.LAddress
  27.             $process.Localport = $matches.LPort
  28.             $process.RemoteAddress = $matches.RAddress
  29.             $process.Remoteport = $matches.RPort
  30.             $process.State = $matches.State
  31.             $process.PID = $matches.PID
  32.             $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName
  33.         }
  34.     }
  35. $process
  36. }

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