begin { # if comparison needs to be case-sensitive, use a # case-sensitive hash table, if ($CaseSensitive) { $hash = [System.Collections.Hashtable]::new() } # else, use a default case-insensitive hash table else { $hash = @{} } }
process { foreach ($elementin$InputObject) { # take the key from the property that was requested # via -Property
# if the user submitted a script block, evaluate it if ($Property-is [ScriptBlock]) { $key = & $Property } else { $key = $element.$Property } # convert the key into a string if requested if ($AsString) { $key = "$key" }
# make sure NULL values turn into empty string keys # because NULL keys are illegal if ($key-eq$null) { $key = '' }
# if there was already an element with this key previously, # add this element to the collection if ($hash.ContainsKey($key)) { $null = $hash[$key].Add($element) } # if this was the first occurrence, add a key to the hash table # and store the object inside an arraylist so that objects # with the same key can be added later else { $hash[$key] = [System.Collections.ArrayList]@($element) } } }
end { # default output are objects with properties # Count, Name, Group if ($AsHashTable-eq$false) { foreach ($keyin$hash.Keys) { $content = [Ordered]@{ Count = $hash[$key].Count Name = $key } # include the group only if it was requested if ($NoElement-eq$false) { $content["Group"] = $hash[$key] }
# return the custom object [PSCustomObject]$content } } else { # if a hash table was requested, return the hash table as-is $hash } } }