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?
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With