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?
I just use the length of the fullname:
gci -recurse | sort @{expression = {$_.fullname.length}} -descending
All child items will get sorted before their parent container.
You could avoid the regular expression and just use the string split method. It also performs better.
dir -recurse | sort -Property @{ Expression = {$_.FullName.Split('\').Count} } -Desc
Result:
TotalMilliseconds : 346.1253
vs...
Get-ChildItem -Recurse | Sort @{Expression={ ( $_.fullname | select-string "\\" -AllMatches ).matches.count }; Descending=$true }
Result:
TotalMilliseconds : 953.6606
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