Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've read plenty of examples but don't seem to be able to find a syntax to sort a list of directories in PowerShell by the length of the full directory name.

This is what I have:

$folderNamePatterns = @( "bin", "obj" )
$deleteFolderList = Get-ChildItem -Path $rootFolder -Recurse -Directory -Include ( $folderNamePatterns ) | Sort-Object -Property DirectoryName.Length
Write-Output "Folder list is:"
for( $i=0; $i -lt $deleteFolderList.Count; $i++ )
{
	Write-Output $deleteFolderList[ $i ].FullName
}


It gives no error but it doesn't sort the list.

I must be missing something frustratingly simple. Can anyone please tell me what?

Kind wishes ~ Patrick

What I have tried:

I've tried all sorts for the -Property argument.
Posted
Updated 23-Jul-18 5:02am

1 solution

Annoyingly, the DirectoryName property doesn't seem to work when you're sorting the results. Neither does the Parent property.

You'll probably need to use Select-Object to add a computed property to the list:
$deleteFolderList = Get-ChildItem -Path $rootFolder -Recurse -Directory -Include ( $folderNamePatterns ) | Select-Object FullName, @{n='l';e={$_.Parent.FullName.Length}} | Sort-Object -Property l

Windows PowerShell Tip of the Week | Microsoft Docs[^]
 
Share this answer
 
Comments
Patrick Skelton 23-Jul-18 11:33am    
Thanks, Richard. I've learnt something but it doesn't seem to quite work for me. I've shown a simplified version of your code below together with its output. As you can see, it seems to 'chop off' the final subdirectory when displaying the length.

PS C:\WINDOWS\system32> Get-ChildItem -Recurse -Directory C:\Temp\Debug | Select-Object FullName, @{n='l';e={$_.Parent.FullName.Length}} | Sort-Object -Property
l

FullName l
-------- -
C:\Temp\Debug\x64 13
C:\Temp\Debug\x86 13
C:\Temp\Debug\Resources 13
C:\Temp\Debug\WorkingFolders 13
C:\Temp\Debug\Resources\Graphics 23
C:\Temp\Debug\WorkingFolders\Temp 28
C:\Temp\Debug\WorkingFolders\Reports 28
C:\Temp\Debug\WorkingFolders\Logs 28
Richard Deeming 23-Jul-18 11:35am    
So you want to sort by the length of the full name, rather than the length of the parent directory's full name?
... | Select-Object FullName, @{n='l';e={$_.FullName.Length}} | ...
Richard Deeming 23-Jul-18 11:37am    
Or, more simply:
$deleteFolderList = Get-ChildItem -Path $rootFolder -Recurse -Directory -Include ( $folderNamePatterns ) | Sort-Object @{Expression={$_.FullName.Length}}
Patrick Skelton 23-Jul-18 11:56am    
Cherry picking your replies, this seems to do what I want: Get-ChildItem -Path C:\Temp -Recurse | Select-Object FullName, @{n='l';e={$_.FullName.Length}} | Sort-Object -Property l

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900