PowerShell doesn't seem to sort objects by name ascending correctly:
dir | Sort-Object Name
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With