Private/Select-SFLatestByGroup.ps1

function Select-SFLatestByGroup {
    [CmdletBinding()]
    [OutputType([object[]])]
    param (
        [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Resources,
        [Parameter(Mandatory)] [hashtable]$Processor
    )

    $groups = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new(
        [System.StringComparer]::Ordinal
    )

    foreach ($resource in $Resources) {
        $groupKey = Get-SFGroupKey -Resource $resource -Fields @($Processor.GroupBy)
        if (-not $groups.ContainsKey($groupKey)) {
            $groups[$groupKey] = [System.Collections.Generic.List[object]]::new()
        }
        $groups[$groupKey].Add($resource)
    }

    foreach ($group in $groups.GetEnumerator()) {
        $sortableResources = foreach ($resource in $group.Value) {
            $entry = [ordered]@{ Resource = $resource }
            $sortIndex = 0
            foreach ($order in @($Processor.OrderBy)) {
                $field = [string]$order.Field
                $value = Get-SFNestedValue -InputObject $resource -Path $field
                $entry["Sort$sortIndex"] = ConvertTo-SFSortValue `
                    -Value $value `
                    -Type ([string]$order.Type) `
                    -Field $field
                $sortIndex++
            }
            [PSCustomObject]$entry
        }

        $sortProperties = for ($sortIndex = 0; $sortIndex -lt @($Processor.OrderBy).Count; $sortIndex++) {
            @{
                Expression = "Sort$sortIndex"
                Descending = ([string]$Processor.OrderBy[$sortIndex].Direction -eq 'Descending')
            }
        }
        $sortedResources = @($sortableResources | Sort-Object -Property $sortProperties)

        if ($sortedResources.Count -gt 1) {
            $sameRank = $true
            for ($sortIndex = 0; $sortIndex -lt @($Processor.OrderBy).Count; $sortIndex++) {
                $sortPropertyName = "Sort$sortIndex"
                if ($sortedResources[0].$sortPropertyName -ne $sortedResources[1].$sortPropertyName) {
                    $sameRank = $false
                    break
                }
            }
            if ($sameRank) {
                throw "LatestByGroup group '$($group.Key)' is ambiguous because its two highest-ranked rows have identical OrderBy values."
            }
        }

        $sortedResources[0].Resource
    }
}