Last active
August 30, 2024 02:22
-
-
Save ariel-co/95b1a0936ec400fa76d4642228e8d17b to your computer and use it in GitHub Desktop.
group-object without sorting first
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Group-NoSort() { | |
| [CmdletBinding()] | |
| Param( | |
| [Parameter(ValueFromPipeline=$true)] $InputObject, | |
| [Parameter(Mandatory, Position=0, | |
| HelpMessage="Name of the property to use as a grouping key")][String] $Property, | |
| [Parameter( | |
| HelpMessage="If true, keys will be compared for full equality (e.g. 2.0 and 2 are not equal)")] | |
| [switch] $StrictEq | |
| ) | |
| Begin { $Group=@(); $Name=$null; } | |
| Process { | |
| $currentName = $_.$Property | |
| if ( | |
| $Group -and | |
| ($StrictEq ? ! [Object]::Equals($currentName, $Name) : ($currentName -ne $Name)) | |
| ) { | |
| [PSCustomObject]@{ | |
| Name = $Name; | |
| Count = $Group.Length; | |
| Group = $Group | |
| } | |
| $Group=@() | |
| } | |
| $Group += $_; $Name=$currentName; | |
| } | |
| End { | |
| if ($Group) { | |
| [PSCustomObject]@{ | |
| Name = $Name; | |
| Count = $Group.Length; | |
| Group = $Group | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment