Making netstat.exe Object-Oriented

by Jul 6, 2012

Netstat.exe is a useful tool, like many other console-based applications. Take a look how relatively easy it is for PowerShell to take the text-based output and convert it into real objects:

netstat -an |
    ForEach-Object {
       $i = $_ | Select-Object -Property Protocol , Source , Destination , Mode
       $null, $i.Protocol, $i.Source, $i.Destination, $i.Mode = 
                ($_ -split '\s{2,}')
       if ($i.Protocol.length -eq 3) { $i }
    }

Since the result is converted to objects, you can now easily use other PowerShell cmdlets to sort or filter the results. This slight variation would i.e. show all listening connections:

netstat -an |
    ForEach-Object {
       $i = $_ | Select-Object -Property Protocol , Source , Destination , Mode
       $null, $i.Protocol, $i.Source, $i.Destination, $i.Mode = 
                ($_ -split '\s{2,}')
       if ($i.Protocol.length -eq 3) { $i }
    } |
    Where-Object { $_.Mode -eq 'LISTENING' }

Like always with console applications, the data may be localized and different on different UI cultures.

Twitter This Tip! ReTweet this Tip!