How can I use powershell to intercept a specified string of a command output?

I use ipptool to get the status of the current print job.

C:\Users\Administrator>ipptool http://localhost/ipp/printers get-completed-jobs.test


job-id job-state job-name job-originating-user-name job-media-sheets-completed

------ --------- -------- ------------------------- --------------------------

14     canceled                RedHat                    1

13     completed               RedHat                    1

12     completed               RedHat                    1

11     completed               RedHat                    1

How do I get the specified job-id and job-state?

What method does Powershell use to intercept strings?

Question 1:

Get the following stringļ¼š

14 canceled

Question 2 :

Get the following string:

13 completed

12 completed

Question 3 :

How do I get the most recent job-id and job-state?

1 answer

  • answered 2018-07-11 06:57 iRon

    The cmdlet ConvertFrom-SourceTable available for download from the PowerShell gallery (GitHub: iRon7/ConvertFrom-SourceTable) is capable of reading this type of data tables:

    $Jobs = ConvertFrom-SourceTable '
    
    job-id job-state job-name job-originating-user-name job-media-sheets-completed
    
    ------ --------- -------- ------------------------- --------------------------
    
    14     canceled                RedHat                    1
    
    13     completed               RedHat                    1
    
    12     completed               RedHat                    1
    
    11     completed               RedHat                    1
    '
    

    In your case, it is probably something like:

    $Jobs = $(.\ipptool http://localhost/ipp/printers get-completed-jobs.test) | ConvertFrom-SourceTable
    

    The rest of your questions are actually a matter of basic PowerShell commands.
    As in this example, the Jobs object will give you access to e.g. the status of job 14:

    $Jobs | ?{$_."job-id" -eq 14} | Select -Expand "job-state"
    canceled
    

    And "How do I get the most recent job-id and job-state?":
    (presuming that the most recent job is always on top)

    $Jobs | Select  "job-id", "job-state" -First 1
    
    job-id job-state
    ------ ---------
    14     canceled
    

    (For other ConvertFrom-SourceTable examples see: https://stackoverflow.com/search?q=ConvertFrom-SourceTable)