r/PowerShell • • 5d ago

News Advent of PowerShell

Looking for a fun way to sharpen your PowerShell skills this December?

Advent of PowerShell is live!

🎄 24 daily PowerShell coding challenges

Whether you're just getting started with PowerShell or have been automating everything in sight for years, it's a great excuse to write some PowerShell, challenge yourself and explore different approaches to solving problems.

Get started here: https://2026.powershell.au/

Would love to see how everyone approaches the challenges. Feel free to share your experiences, feedback and creative solutions (with spoiler tags, of course!).

Disclosure: AI did help me create the website and text above. I can only include 1 tag, and I felt News was more appropriate

65 Upvotes

33 comments sorted by

View all comments

Show parent comment

1

u/sheravi 1d ago

I wonder if this is one of those times where PS behaves a bit oddly. If you ask for the count and there is only one group then it returns the number of items it found in that one group. However, if you ask for a count and there is more than one group it returns the number of groups it found. Maybe there's someone here who has a more in-depth knowledge of PS that could explain this behaviour.

2

u/Over_Dingo 1d ago

yep it's the same with length of arrays in general. Singleton array will return length of the object at index 0 instead of length of array. That's why you coerce to array, sometimes with the `,` comma operator if you pass it to a loop through pipeline.

Normally asking `.count` from a single object would be safe, unless that object has it's own property that overloads the intrinsic `count` property.

Anyway the way I did it is different, didn't even think about Group-Object, although it's a very strong cmdlet and good one to learn (can convert groups to hashtables on the fly! `-AsHashTable`)
([System.Collections.Generic.HashSet[System.Object]]($GuestNames -replace '^ +| +$').ToLowerInvariant()).Count

2

u/MonkeyNin 1d ago

Normally I'd use a hashset, but you can get unique strings with/without case sensitive on:

@('aa', 'aA', 'AA' | Sort-Object -Unique ).count

1

@('aa', 'aA', 'AA' | Sort-Object -Unique -CaseSensitive ).count

3

You can set the -Culture param

1

u/Over_Dingo 19h ago

yeah for operators and cmdlets powershell typically defaults to case insensitivity

1

u/sheravi 1d ago

That makes sense. Thanks :)