Skip to content

Instantly share code, notes, and snippets.

@ariel-co
Last active August 30, 2024 02:22
Show Gist options
  • Select an option

  • Save ariel-co/95b1a0936ec400fa76d4642228e8d17b to your computer and use it in GitHub Desktop.

Select an option

Save ariel-co/95b1a0936ec400fa76d4642228e8d17b to your computer and use it in GitHub Desktop.
group-object without sorting first
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