7

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
dev-masih
  • 4,188
  • 3
  • 33
  • 55
Suman Ghosh
  • 1,317
  • 3
  • 12
  • 18

1 Answers1

10

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}
Community
  • 1
  • 1
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206