PoshCode Logo PowerShell Code Repository

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

This will perform a basic netstat.exe command and “objectize” its output. This version only handles the TCP stuff because I ran out of time. This needs perhaps a switch statement and a second regex to do the rest justice.

I’d like to see in a v2 the capability to tie process names in via the PID column and output the real process name and file info and so on.

  1. $null, $null, $null, $null, $netstat = netstat -a -n -o
  2. [regex]$regex = '\s+(?<Protocol>\S+)\s+(?<LocalAddress>\S+)\s+(?<RemoteAddress>\S+)\s+(?<State>\S+)\s+(?<PID>\S+)'
  3.  
  4. $netstat | ForEach-Object {
  5.        if ( $_ -match $regex ) {
  6.                $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress,
  7. State, PID
  8.                $process.Protocol = $matches.Protocol
  9.                $process.LocalAddress = $matches.LocalAddress
  10.                $process.RemoteAddress = $matches.RemoteAddress
  11.                $process.State = $matches.State
  12.                $process.PID = $matches.PID
  13.                $process
  14.        }
  15. }

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