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