Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group-Object on an array?

Tags:

powershell

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)
like image 759
ca9163d9 Avatar asked Oct 30 '25 19:10

ca9163d9


1 Answers

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.
like image 50
Mathias R. Jessen Avatar answered Nov 04 '25 02:11

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!