Reputation: 1539
I have list of directories. Directories are named as numbers. How to sort the directory name in numeric order by power shell.
Name
-----
1
12
2
Upvotes: 8
Views: 12658
Reputation: 174835
The sort order is based on the type of the property being used for comparison.
Since the Name
property of your directories are of type [string]
, alphabetical sorting takes place, which ranks 10
before 9
(because the first character 1
precedes the character 9
in alphabetical order).
To sort the numbers by numeric value, use a scriptblock (as shown in the comments) or a calculated expression to cast the value to a numeric type:
Get-ChildItem -Directory | Sort-Object -Property {$_.Name -as [int]}
Using -as
, rather than a cast will prevent exceptions for objects where the Name
property cannot be converted to [int]
. The -as
type operator is introduced in PowerShell version 3.0, so for earlier versions, use a regular cast:
Get-ChildItem -Directory | Sort-Object -Property {[int]$_.Name}
Upvotes: 11