Search code examples
powershellsplitchocolateyselect-string

Use Powershell to match and print specific column from output


I want to fetch a specific column from an output of a command. Can someone please suggest what is the best way to do it?

The command used is - choco list -lo which gives the output as

Chocolatey v0.10.15
chocolatey 0.10.15
erlang 22.3
rabbitmq 3.8.11
3 packages installed.

And from the given output the only required value is 3.8.11 which is the version of rabbitmq.

I have already tried this but it does not work - choco list -lo | Select-String -Pattern "rabbit" | %{ $_.Split(' ')[1]; }

Can someone suggest how can we do this?

Thanks in advance :)


Solution

  • Try this:

    choco list -lo | 
        Select-String -Pattern "rabbitmq (.+)" | 
        ForEach-Object { $_.Matches.Groups[1].Value }
    

    Output of Select-String is a MatchInfo object, so you need to query its members to get the matched value.

    I'm using a group (.+) to enable extraction of the version number without further string operations. The groups value is then read in the ForEach-Object 1 script block through $_.Matches.Groups[1].Value. In this expression the index 1 specifies the first group (index 0 would specify the whole match).


    [1] ForEach-Object is abbreviated by %