Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Sort-Object by [DateTime]::ParseExact

Tags:

powershell

I'm trying to sort the lines returned by a console program by date, using PowerShell.

The dates are formated in MM/dd/yyyy format, so they have to be converted to DateTime objects to be in a sortable format.

To parse the dates, I use:

$dates = %{ "10/24/2010", "02/03/2010" }
$dates | %{ [System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null) }

This parses the dates into System.DateTime objects and displays their default ToString() representation, but it also shows an additional blank line at the beginning.

Now, if I try to sort the dates with Sort-Object, I get an error message, and I guess the error comes from the additional blank line:

$sortedDates = $dates | Sort-Object [System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null)

Error message:

"Sort-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'."

Where is the extra blank line coming from? Am I doing something wrong to parse the dates, or to sort them?

like image 532
ckarras Avatar asked Feb 24 '23 09:02

ckarras


1 Answers

I think part of the problem is in the first line.

%{ } means foreach-object { }.

I think you meant @( , ). You don't really even need the @( ).

$dates= "10/24/2010", "02/03/2010"  

works fine.
To sort by a "derived field", use a scriptblock.

$sortedDates = $dates | Sort-Object {[System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null)}
like image 198
Mike Shepard Avatar answered Mar 04 '23 23:03

Mike Shepard