Home > Blockchain >  PowerShell - sort, top
PowerShell - sort, top

Time:12-09

Can I ask for help,

I have date - "comp name" and "Date", in $value e.g.

|"Comp Name"|  "Date"   |
|:----------|----------:|
|computer1  | 2021-12-02|
|Computer2  | 2021-10-02|
|computer3  | 2021-08-02|
|computer1  | 2021-11-02|
|computer2  | 2021-12-02| 
|computer3  | 2021-12-02| 
|computer1  | 2021-10-02|
|computer4  | 2021-09-23| 
|computer2  | 2021-09-02|
|computer3  | 2021-12-02| 
|computer4  | 2021-12-07|

Now I want to sort it by date and give the top 1 which means that it expects the result.

|"Comp Name"|  "Date"   |
|:----------|----------:| 
|computer1  |2021-12-02 | 
|computer2  |2021-12-02 |
|computer3  |2021-12-02 | 
|computer4  |2021-12-07 |

And I used:

$list | Sort-Object -Property Date -Descending | Select-Object -First 1

but I only get this, computer1 2021-12-02, how to enter it correctly

CodePudding user response:

Sounds like you want to Group by Comp Name, and then select max Date for each group?

$list | Group-Object -Property 'Comp Name' | ForEach-Object { $_.Group | Sort-Object Date -Descending | Select-Object -First 1 }

*Old (Based off of original requirement): One way is to obtain the max value, then iterate through the list again, filtering with the Where-Object cmdlet:

$max = $list | Sort-Object -Property Date -Descending | Select-Object -First 1

$list | Where-Object { $_.Date -eq $max.Date } | Sort-Object -Property 'Comp Name' | Get-Unique -AsString
  • Related