Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Sort-Object by Name Ascending

PowerShell doesn't seem to sort objects by name ascending correctly:

dir | Sort-Object Name

enter image description here

My goal is to sort the elements in this order:

1.sql
2.sql
3.sql
...
9.sql
10.sql
11.sql
...

Is there a way to solve this?

like image 460
Francesco Mantovani Avatar asked Jan 28 '23 17:01

Francesco Mantovani


1 Answers

You need to sort the filenames as numbers, rather than as text. It's convenient because the filenames in your example are entirely numbers, so you can change the sort to use a dynamic scriptblock property, which will evaluate the filename to a number for each item in the pipeline:

| sort-object -Property {
    if (($i = $_.BaseName -as [int])) { $i } else { $_ }
}

That means: if the filename can be converted to an integer, then use that, otherwise use it as it is.

like image 198
TessellatingHeckler Avatar answered Jan 30 '23 07:01

TessellatingHeckler