I'm trying to sort a CSV file by multiple columns including a date column. The date is in the format of dd-MMM-yyyy or 03-Jun-2021. However, parseexact isn't seeing the value as date I think as it's sorting it based upon day values only. ie: 03-Jun-2021 befour 25-Apr-2021
When I look at the cell in Excel it's a "general" value not date, but I thought parsexact should convert this.
What I am trying to do is sort this based upon "ID" column, "Access Type", "Start Date", and finally by Rotation.
My code line is:
Import-csv $Source | Select-Object * |
Sort-Object @{Expression="ID";Descending=$true},@{Expression="Access Type",@{Expression={[datetime]($_."Start Date")};Descending=$false},@{Expression="Rotation";Descending=$true} | Export-Csv $destination -Encoding Default -NoTypeInformation
What I'm finding is that if I do a sort on Rotation Date alone it seems to work and sort properly. When I sort by multiple columns, the date column doesn't appear to sort correctly and sorts by the day of dd-MMM-yyyy.
I've attached a sample CSV:
Thank you and sorry about not being clear originally.
CodePudding user response:
Both, scriptblock
and hashtable
sorting work fine :
@'
Start Date
03-Jun-2021
25-Apr-2021
04-Jun-2021
10-Apr-2021
'@ | ConvertFrom-Csv | Sort-Object {
[datetime]$_.'Start Date'
}
Start Date
----------
10-Apr-2021
25-Apr-2021
03-Jun-2021
04-Jun-2021
@'
Start Date
03-Jun-2021
25-Apr-2021
04-Jun-2021
10-Apr-2021
'@ | ConvertFrom-Csv | Sort-Object @{
expression = {[datetime]$_.'Start Date'}
}
Start Date
----------
10-Apr-2021
25-Apr-2021
03-Jun-2021
04-Jun-2021
CodePudding user response:
Please ignore this question.
The cause was my own error. I was misspelling at column title which lead my down the wrong path.
Import-csv $Source | Select-Object * |
Sort-Object @{Expression="ID";Descending=$true},@{Expression="Access Type"},@{Expression={[datetime]($_."Start Date")};Descending=$false} | Export-Csv -path $output
Works as expected.
Sorry everyone!