Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I control the order of processing items in/from get-childitem -recurse

Tags:

powershell

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?

like image 413
onupdatecascade Avatar asked Dec 27 '22 05:12

onupdatecascade


2 Answers

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.

like image 34
mjolinor Avatar answered May 12 '23 08:05

mjolinor


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
like image 93
Andy Arismendi Avatar answered May 12 '23 08:05

Andy Arismendi