Split text by columns in PowerShell

Honestly I’d look up a better way to do this, but you can fudge it with some text manipulation and the ConvertFrom-Csv cmdlet:

$(qwinsta.exe) -replace "^[\s>]" , "" -replace "\s+" , "," | ConvertFrom-Csv | select username

Firstly replace any leading spaces or > characters with nothing, then replace any white spaces with a comma. Then you can pipe to ConvertFrom-Csv and work with the data as an object.

EDIT

Actually, the above has some issues, mostly with the \s+ because if a column is blank it does not get correctly recognised as a blank field, and the next text is incorrectly promoted to the current field.

The below is a full blown parser for this command, and would probably work for any sort of tabulated output from a native windows exe:

$o = @()
$op = $(qwinsta.exe)

$ma = $op[0] | Select-String "(?:[\s](\w+))" -AllMatches
$ErrorActionPreference = "Stop"

for($j=1; $j -lt $op.length; $j++) {
    $i = 0
    $obj = new-object pscustomobject
    while ($i -lt $ma.matches.count) { 
      $prop = $ma.matches[$i].groups[1].value; 
      $substrStart = $ma.matches[$i].index 
      $substrLen = $ma.matches[$i+1].index - $substrStart
      try {
        $obj | Add-Member $prop -notepropertyvalue $op[$j].substring($substrStart,$substrLen).trim() 
      }
      catch [ArgumentOutOfRangeException] {
        $substrLen = $op[$j].length - $substrStart 
        if($substrLen -gt 0) {
          $obj | Add-Member $prop -notepropertyvalue $op[$j].substring($substrStart,$substrLen).trim()
        }
        else {
          $obj | Add-Member $prop -notepropertyvalue ""
        }
      }
      $i++
    }
    $o += ,$obj
}

$o | ? { $_.type -eq 'rdpwd'} | select username

USERNAME
--------
user.name1
user.name2
user.name3

Leave a Comment