powershellpowershell-cmdletwindows-11powershell-7.2

How to make netstat output's headings show properly in out-gridview?


enter image description here

when I use:

netstat -f | out-gridview

in PowerShell 7.3, I get the window but it has only one column which is a string. I don't know why it's not properly creating a column for each of the headings like Proto, Local Address etc. how can I fix this?


Solution

  • While commenter Toni makes a good point to use Get-NetTCPConnection | Out-GridView instead, this answer addresses the question as asked.

    To be able to show output of netstat in grid view, we have to parse its textual output into objects.

    Fortunately, all fields are separated by at least two space characters, so after replacing these with comma, we can simply use ConvertFrom-CSV (thanks to an idea of commenter Doug Maurer).

    netstat -f | 
        # Skip unwanted lines at the beginning
        Select-Object -skip 3 | 
        # Replace two or more white space characters by comma, except at start of line
        ForEach-Object { $_ -replace '(?<!^)\s{2,}', ',' } |
        # Convert into an object and add it to grid view
        ConvertFrom-Csv | Out-GridView
    

    For a detailed explanation of the RegEx pattern used with the -replace operator, see this RegEx101 demo page.


    This is the code of my original answer, which is functionally equivalent. I'll keep it as an example of how choosing the right tool for the job can greatly simplify code.

    $headers = @()
    
    # Skip first 3 lines of output which we don't need
    netstat -f | Select-Object -skip 3 | ForEach-Object {
       
        # Split each line into columns
        $columns = $_.Trim() -split '\s{2,}'
       
        if( -not $headers ) {
            # First line is the header row
            $headers = $columns
        }
        else {
            # Create an ordered hashtable
            $objectProperties = [ordered] @{}
            $i = 0
            # Loop over the columns and use the header columns as property names
            foreach( $key in $headers ) {
                $objectProperties[ $key ] = $columns[ $i++ ]
            }
            # Convert the hashtable into an object that can be shown by Out-GridView
            [PSCustomObject] $objectProperties
        }
    } | Out-GridView