Blog Post

#PowershellBasics: Sort a list

,

In my last post I grabbed a file list but I really need it sorted alphabetically. Now, I’ve been a DBA my entire career and one of the things that gets hammered into you is that unless you specifically sort a list, there is no guarantee that that list will be sorted. So how do I sort my list? With the surprisingly named Sort-Object.

$Path = "C:temp"
get-childitem -path $Path -filter *.csv -name | sort-object 

comments.csv
Employee.csv
test1.csv

I want to point out a couple of things here. First, the default property is name. So if you are sorting something specifically called name you don’t have to include the -property parameter. Second, if you do include the -property parameter and that parameter doesn’t exist you’ll get .. well .. I’ll be honest I haven’t figured out what order you’ll get.

$Path = "C:temp"
# Property I want to sort on does not exist.
get-childitem -path $Path -filter *.csv -name | sort-object -property LastWriteTime

Employee.csv
comments.csv
test1.csv

vs

$Path = "C:temp"
# Property I want to sort on does exist
get-childitem -path $Path -filter *.csv | sort-object -property LastWriteTime
Directory: C:temp

Mode LastWriteTime Length Name
—- ————- —— —-
-a—- 6/27/2021 11:26 AM 66 Employee.csv
-a—- 7/12/2021 5:15 PM 245609 test1.csv
-a—- 7/30/2021 7:04 PM 62443 comments.csv

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating