Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of paths in Powershell

I am trying to sort (from deepest folder to root) a list of given paths.

Is there a way to achieve this with existing functions?

Example:

Given:

test\A\directory1
test\B
test\A\directory1\end
test\A
test\C\directory2
test
test\C
test\directdirectory

To obtain:

test\C\directory2
test\A\directory1
test\directdirectory
test\C
test\B
test\A
test
like image 820
Adrian Ileana Avatar asked Nov 22 '18 11:11

Adrian Ileana


People also ask

Which PowerShell cmdlet can be used to sort a list?

Description. 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 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.

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 a hash table in PowerShell?

To sort a hashtable, use the GetEnumerator() method on the hashtable to gain access to its individual elements. Then use the SortObject cmdlet to sort by Name or Value.


1 Answers

You can use an expression in your sort command to sort by the amount of \

Sort {($_ -split '\\').Count}, {$_} -Descending

Example kudos to LotPings

@(
'test\A\directory1'
'test\B'
'test\A\directory1\end'
'test\A'
'test\C\directory2'
'test'
'test\C'
'test\directdirectory'
) | Sort {($_ -split '\\').Count}, {$_} -Descending

Result

test\A\directory1\end
test\C\directory2
test\A\directory1
test\directdirectory
test\C
test\B
test\A
test

Edit: is sorting on the second key necessary the jury is still out on that

Sorting on a second key difference

like image 191
Lieven Keersmaekers Avatar answered Oct 10 '22 00:10

Lieven Keersmaekers