Powershell – In PowerShell, how can I parse a preformatted output

command-line-interfaceformattingparsingpowershellpowershell-v3.0

Is there existing tooling to take text-based output and pipe it to a dynamic object that can be queried as columns?

Specifically, I'm invoking ..

query session /server:MYSERVER

.. which is outputting ..

SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE 
services                                    0  Disc                        
console           Jon                       1  Active  

This is my first task in a DevOps role, to act upon this output based on conditions of the columns, but after multiple tries to pipe into foreach etc I realized that it's all just multiple lines of strings.

What I was hoping for was something like ..

query session /server:MYSERVER | foreach `
{ `
    if ($_.Username -eq "Jon") `
    {`
        custom-action $_.ID `
    } `
}

(Note that I do not necessarily need to evaluate the Username, or not only the Username, I am only doing so in this example.)

Obviously this won't work because this ..

query session /server:192.168.1.103 | foreach { echo $_.GetType() }

.. outputs this ..

IsPublic IsSerial Name                                     BaseType                                                    
-------- -------- ----                                     --------                                                    
True     True     String                                   System.Object                                               
True     True     String                                   System.Object                                               
True     True     String                                   System.Object     

The only solution I've found is manually extracting the columns using String.Substring(). I was hoping there was PowerShell tooling that automated this.

[[This is an example,]] but some columns are blank, and the fixed-width columns are not the same width between each other, so parsing this would be much more manual than the examples there. I was hoping that Powershell version updates might have better tooling perhaps?

Using Windows Server 2012 R2 (which has PowerShell 4).

Best Answer

There is nothing built in.

However it shouldn't be too hard to create a helper (in a module for easy reuse of course) that takes a definition of each column (eg. name, starting position, length, type, ...; or perhaps alternate criteria to separate the columns if lengths cannot be pre-determined) and creates a custom object.