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
The Sort-Object cmdlet sorts objects in ascending or descending order based on object property values. If sort properties are not included in a command, PowerShell uses default sort properties of the first input object.
You can sort different properties in different orders by using hash tables in an array. Each hash table uses an Expression key to specify the property name as string and an Ascending or Descending key to specify the sort order by $true or $false . The Expression key is mandatory.
There are actually two ways to do this. The first way to do this is to use the Sort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the static Sort method from the System. Array .
To sort the output in the PowerShell you need to use Sort-Object Pipeline cmdlet. In the below example, we will retrieve the output from the Get-Process command and we will sort the, according to memory and CPU usage.
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}
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