In the previous tip we showed that Sort-Object accepts property names, hash tables or plain script blocks to sort things. Let’s check out why submitting script blocks to Sort-Object can be a good idea.

Let’s assume you have a bunch of string data that represents dates, and you’d like to sort them:

 
PS> 'May 12, 2020', 'Feb 1, 1999', 'June 12, 2021' | Sort-Object

Feb 1, 1999
June 12, 2021
May 12, 2020  
 

The result is sorted, but not by date. Since the input was strings, Sort-Object used alphanumeric sort algorithms. You could now convert the original data to another format and sort it.

Yet, you can also ask Sort-Object to do the conversion. The difference would be that the original data format remains untouched: a series of strings would be sorted by date, yet remain strings:

 
PS> 'May 12, 2020', 'Feb 1, 1999', 'June 12, 2021' | 
       Sort-Object -Property { [DateTime]$_ }

Feb 1, 1999
May 12, 2020
June 12, 2021 
 

Of course, it is your job to come up with a script block that correctly transforms the incoming raw data in $_ to the desired type you want to use for sorting. With dates, you might also want to look into the -as operator which uses the local date and time formats whereas a direct cast always uses US format:

 
PS> 'May 12, 2020', 'Feb 1, 1999', 'June 12, 2021' | Sort-Object -Property { $_ -as [DateTime] }

Feb 1, 1999
May 12, 2020
June 12, 2021 
 




Twitter This Tip! ReTweet this Tip!

Anonymous