Search code examples
powershellget-childitem

Iterating recursively in alphabetic, depth-first order?


How do I iterate through a folder so that I respect the alphabetic (lexical) order, but recurse into any directories before moving on to the next item of the old directory?

Sample structure for clarification:

Alpha
  |- 1.txt
  |- 2.txt
  |- 3
  |  |- a.txt
  |  \- b.txt
  \- 4.txt
Beta
  \- Test
     \- Another
        \- File.txt

I'd like to iterate in such a way that, were I were to print all the items that came by, the result would look as follows:

Alpha
1.txt
2.txt
3
a.txt
b.txt
4.txt
Beta
Test
Another
File

However, I can't seem to figure out how to properly do both the recursion and the ordering without making a really nasty mess of nested Get-ChildItem with manual recursion, but I am hopeful that there is a neater way that I can also learn from.

If this is too difficult to implement for some reason, reserving the order at which the items are processed is the bottom line of what matters to me as I can make do without preserving the tree structure if I have to.


Solution

  • No need for manual recursion, Get-ChildItem will do what you want when you also use Sort-Object and Select-Object.

    • Get-ChildItem with Recurse to get your item list
    • sort by FullName to put the items in the order you want
    • select the Name property to show just the items Name

    Gives:

    Get-ChildItem C:\folder -Recurse | sort FullName | select -ExpandProperty Name
    
    Alpha
    1.txt
    2.txt
    3
    a.txt
    b.txt
    4.txt
    Beta
    Test
    Another
    file.txt