Question:
Trying to educate myself: when processing a whole tree of items from
get-childitem -recurse
I often have to do it from the leaf level up to the top level (for example, deleting files and folders, it’s problemmatic to modify the upper levels of the tree and then attempt to deal with the lower levels.
To work around this, I’ve resorted to sorting the whole collection by the number of delimiters in the paths, to get the leaf level first, followed by upper levels of the tree:
$someFiles = Get-ChildItem -Recurse |
Sort @{Expression={ ( $_.fullname | select-string "\\" -AllMatches ).matches.count };
Descending=$true }
This feels wrong – I have limited coding experience, but I know that if I just traverse the tree in the right way, this expensive and goofy sort should not be necessary. But -recurse is so handy!
What’s the smarter way to do this? To be specific, is there a way to traverse the tree with get-childitem, from leaf up, that does not require sorting all the results?
Answer:
You could avoid the regular expression and just use the string split method. It also performs better.
1 2 |
dir -recurse | sort -Property @{ Expression = {$_.FullName.Split('\').Count} } -Desc |
Result:
1 2 |
TotalMilliseconds : 346.1253 |
vs…
1 2 |
Get-ChildItem -Recurse | Sort @{Expression={ ( $_.fullname | select-string "\\" -AllMatches ).matches.count }; Descending=$true } |
Result:
1 2 |
TotalMilliseconds : 953.6606 |