Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Directory name using Powershell

Tags:

powershell

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
like image 649
Suman Ghosh Avatar asked Nov 12 '15 05:11

Suman Ghosh


People also ask

What is sort command in PowerShell?

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.

How do I sort a table in PowerShell?

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.

How do I sort an array in PowerShell?

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 .

How do you sort a process in PowerShell?

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.


1 Answers

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}
like image 131
Mathias R. Jessen Avatar answered Oct 08 '22 04:10

Mathias R. Jessen