4

How to use Group-Object on the first two columns (a, b) and (c, e) of the following array?

$a = @('a','b','x',10), 
@('a','b','y',20), 
@('c','e','x',50), 
@('c','e','y',30)

1 Answer 1

9

Group-Object accepts anonymous calculated properties, in place of property names:

PS C:\> $a | Group-Object @{ Expression={$_[0]} },@{ Expression = {$_[1]} }

It also accepts a ScriptBlock:

PS C:\> $a | Group-Object {$_[0]},{$_[1]}

As long as the expression can be evaluated to a string:

PS C:\> Get-Help Group-Object -Parameter Property

-Property [<Object[]>]
    Specifies the properties for grouping. The objects are arranged into groups 
    based on the value of the specified property.

    The value of the Property parameter can be a new calculated property. 
    To create a calculated, property, create a hash table with an Expression key
    that specifies a string or script block value.
Sign up to request clarification or add additional context in comments.

4 Comments

Just a note that anonymous is key here. If you supply a label with a hash it does nothing. ie @(1,2,3) | group-object @{l='mod';e={$_ % 2 -eq 0}} does nothing but removing l='mod' will work.
@Fredrick What version of PowerShell are you using? In 5.1 and up, it's correctly validated and a DictionaryKeyIllegal error is thrown
@MathiasRJessen I see. I get the exception with 7.0.0-preview.4 but not 7.0.0-preview.2.
@Fredrick interesting. Might be a temporary regression in between, I haven't been keeping a close eye on changes to the utility cmdlets lately

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.