1

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

Or make them objects instead of hashtables:

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

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

The docs default to powershell 7, which I'm not a fan of.

Comments

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.