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?
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.
For more complex patterns enclosed in alphabetic characters use $ToNatural which expands all embedded numbers to a unique length (here 20) by left padding with zeros.
Source: Roman Kuzmin - How to sort by file name the same way Windows Explorer does?
$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20,"0") }) }
Generate some test data:
> (10..11 + 100..101 + 1..2)|%{new-item -itemtype file -path ("pre_{0}_post.sql" -f $_)
Directory: A:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2018-07-27 11:02 0 pre_10_post.sql
-a---- 2018-07-27 11:02 0 pre_11_post.sql
-a---- 2018-07-27 11:02 0 pre_100_post.sql
-a---- 2018-07-27 11:02 0 pre_101_post.sql
-a---- 2018-07-27 11:02 0 pre_1_post.sql
-a---- 2018-07-27 11:02 0 pre_2_post.sql
> dir| sort
Directory(: A:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2018-07-27 11:02 0 pre_1_post.sql
-a---- 2018-07-27 11:02 0 pre_10_post.sql
-a---- 2018-07-27 11:02 0 pre_100_post.sql
-a---- 2018-07-27 11:02 0 pre_101_post.sql
-a---- 2018-07-27 11:02 0 pre_11_post.sql
-a---- 2018-07-27 11:02 0 pre_2_post.sql
> dir|sort $ToNatural
Directory: A:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2018-07-27 11:02 0 pre_1_post.sql
-a---- 2018-07-27 11:02 0 pre_2_post.sql
-a---- 2018-07-27 11:02 0 pre_10_post.sql
-a---- 2018-07-27 11:02 0 pre_11_post.sql
-a---- 2018-07-27 11:02 0 pre_100_post.sql
-a---- 2018-07-27 11:02 0 pre_101_post.sql