October 26, 2021 by Kenneth Fisher
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
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
$Path = "C:\temp\" # Property I want to sort on does exist get-childitem -path $Path -filter *.csv | sort-object -property LastWriteTime
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