Home > Net >  Display Maximum duplicate value if exist in Powershell
Display Maximum duplicate value if exist in Powershell

Time:09-06

$Export_ByDates = $GetMyImport | Group-Object Ddate, LastName | ForEach-Object {

        if($_.Group | Where Ddate -eq $GetDates) {
            New-Object PSObject -Property @{
                LastName = ($_.Group.LastName -join ',')
                Date = ($_.Group.Ddate -join ',')
                Sum = ($_.Group | Measure-object Donate -sum).Sum
        }
    }
} | Sort-Object Sum -Descending
$Export_ByDates | Select -Property Date, LastName, Sum -First 1 | Export-Csv $Export_ByDater -NoTypeInformation

This is working great; however, I stumbled across 3 donation values that are the same and are the highest donation. My question is, how do I get it to display all three records if they're the same and are the highest number?

Records:

Ddate | LastName | Donate
12/25/2021 | Lee | 100
12/25/2021 | Frank | 50
12/25/2021 | Macy | 100
12/25/2021 | Lee | 20
12/25/2021 | Mark | 120
12/25/2021 | Jackson | 120

CodePudding user response:

You can store the maximum sum value in a variable and then use that to query the object. Replacing the last line in your code sample with the following should work:

$maxsum = $Export_ByDates | 
Select -ExpandProperty Sum -First 1 

$Export_ByDates | 
Where-Object {$_.Sum -eq $maxsum} | 
Export-Csv $Export_ByDater -NoTypeInformation
  • Related