powershellgrouping

What is the problem with Group-Object sample?


What's wrong on me if I'm taking Microsoft's sample and it doesn't work?

enter image description here

The sample command and the expected result:

@(
    @{ name = 'a' ; weight = 7 }
    @{ name = 'b' ; weight = 1 }
    @{ name = 'c' ; weight = 3 }
    @{ name = 'd' ; weight = 7 }
) | Group-Object -Property weight -NoElement

Count Name
----- ----
    1 1
    1 3
    2 7

The latest Windows 10 Enterprise 22H2.


Solution

  • This issue isn't reproducible in PowerShell 7 latest, but in Windows PowerShell 5.1 Group-Object with a string property (-Property weight) doesn't know how to handle incoming hash tables (@{ ... }) from pipeline but you can help it using a calculated expression instead:

    @(
        @{ name = 'a' ; weight = 7 }
        @{ name = 'b' ; weight = 1 }
        @{ name = 'c' ; weight = 3 }
        @{ name = 'd' ; weight = 7 }
    ) | Group-Object -Property { $_.weight } -NoElement