Use Powershell to match and print specific column from output

Viewed 575

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 :)

2 Answers

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 %

There is no comma to split on based on what you posted. It's a space...

I don't have choco installed, because I don't have a use case for it. So, a pseudo list is being:

Option1:

Clear-Host
$ChocoList = @'
Chocolatey v0.10.15
chocolatey 0.10.15
erlang 22.3
rabbitmq 3.8.11
'@ -Split "`n"

$ChocoList | 
ForEach {
    (
        $PSItem | 
        Select-String -Pattern 'rabbitmq'
    ) -Split (' ')
}
# Results
<#
rabbitmq
3.8.11
#>

Option2

([regex]::Matches($ChocoList,'rabbitmq.*').Value -split ' ')
# Results
<#
rabbitmq
3.8.11
#>

Upadated as per my comment back to yours - Option1:

Clear-Host
$ChocoList = @'
Chocolatey v0.10.15
chocolatey 0.10.15
erlang 22.3
rabbitmq 3.8.11
'@ -Split "`n"

($ChocoList | 
ForEach {
    (
        $PSItem | 
        Select-String -Pattern 'rabbitmq'
    ) -Split (' ')
})[1]
# Results
<#
3.8.11
#>

Updated as per my comment back to yours - Option2

([regex]::Matches($ChocoList,'rabbitmq.*').Value -split ' ')[1]
# Results
<#
3.8.11
#>
Related