Search code examples
powershellpowershell-5.0

How to filter rows in the powershell which are taken from console program?


I have an .exe console program which put the result into the console in the following format:

 ------------------ ----------- ----------------
  CompanyName        CompanyId   CompanyType
 ------------------ ----------- ----------------
  test1              1           Root
  test2              2           Center
  test3              3           Company
 ------------------ ----------- ----------------

I would like to pick up this in a PowerShell script and filter by the CompanyName.

I tried it with:

MyTool.exe companies | where {$_.CompanyName -eq 'test1'}

but it seems that this doesn't work.


Solution

  • Here is one way to convert the output of an EXE to a powershell collection of objects. what it does ...

    • creates a fake version of the output of your exe file
    • filters out the lines with repeated hyphens
    • replaces leading spaces with nothing
    • replaces 2-or-more spaces with a comma
    • converts that CSV-like string array into a collection of powershell objects

    here's the code [grin] ...

    # fake getting string output from an EXE
    $InStuff = @'
     ------------------ ----------- ----------------
      CompanyName        CompanyId   CompanyType
     ------------------ ----------- ----------------
      test1              1           Root
      test2              2           Center
      test3              3           Company
     ------------------ ----------- ----------------
    '@ -split [environment]::NewLine
    
    $CompanyInfo = $InStuff -notmatch '--{2,}' -replace '^ {1,}' -replace ' {2,}', ',' |
        ConvertFrom-Csv
    
    $CompanyInfo
    '=' * 30
    $CompanyInfo -match 'Test1'
    

    output ...

    CompanyName CompanyId CompanyType
    ----------- --------- -----------
    test1       1         Root       
    test2       2         Center     
    test3       3         Company    
    ==============================
    test1       1         Root