6

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?

2 Answers 2

9

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)}
Sign up to request clarification or add additional context in comments.

Comments

0

For reference, if anyone has a similar problem, here is my complete solution (based on the accepted answer)

I'm sorting the output of tf.exe labels (TFS command line) by date, and then getting the most recent label:

$lines = tf labels | Select-Object -skip 2 # Skip the header lines
$sortedLines = $lines | Sort-Object { [DateTime]::ParseExact(($_ -split '\s+')[2],"M/d/yyyy",$null) }

$labels = $sortedLines | %{ ($_ -split '\s+')[0] } # get the first column

$latestLabel = $labels[-1] # Last item in the list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.