Home > Software engineering >  Sort powershell hashtable by date property
Sort powershell hashtable by date property

Time:12-21

I have a hashtable with about 1000 items with one of the property is a date

$ht=@{}
$ht[1]=@{Date="11/11/2021"; Number=03321}
$ht[2]=@{Date="10/10/2021"; Number=03321}
$ht[3]=@{Date="09/10/2021"; Number=03321}
# .....

An so on
I need to select 10 records with oldest date - any idea how I could do it?
Thanks

CodePudding user response:

I would convert this Hashtable containing numbered hashtables into an array of PsCustomObjects, making sorting and selecting much easier:

$ht=@{}
$ht[1]=@{Date="11/11/2021"; Number=03321}
$ht[2]=@{Date="10/10/2021"; Number=03321}
$ht[3]=@{Date="09/10/2021"; Number=03321}

# convert to array of PsCustomObjects
$ht.GetEnumerator() | ForEach-Object { [PsCustomObject]$_.Value } |
Sort-Object {[datetime]::ParseExact($_.Date, 'dd/MM/yyyy', $null)} |
Select-Object -First 10

This will result in an array of objects, having properties Number and Date, sorted by date.

CodePudding user response:

the following script is for ascending by date.If descending add -descending in sort-object, also please change your number of records in select-object

$ht=@{}
$ht[1]=@{Date="11/11/2021"; Number=03320}
$ht[2]=@{Date="10/10/2021"; Number=03321}
$ht[3]=@{Date="09/10/2021"; Number=03329}

$ht.GetEnumerator()| Sort-Object {$_.Value.Date} | Select-Object -First 2 | ForEach-Object { Write-Host $_.Value.Date $_.Value.Number }
  • Related