Using AppleScript, how can I loop through all folders and sub-folders within the selected parent folder of Finder?
I'm trying to collapse all child folders/sub-folders so that navigating anywhere under the currently selected folder will not display any expanded folders that were remembered on previous and forgotten searches. I primarily navigate Finder in List view and find it disorienting when I'm presented with a screen of randomly expanded folders. It'd be easier to see folders as they would be displayed from a "fresh start" - no expansions.
I've used Shortcuts & Automator to create simple apps (Quick Actions, Workflows and Services) that can be called using my function keys. So now when I press F12 in Finder, it does the following:
on run {input, parameters}
tell application "System Events"
keystroke "a" using command down
key code 123 using control down --left arrow
key code 126 using option down --up arrow
end tell
return input
end run
This works fine but only takes care of the first level down. I'd like to have it iterate down through all the sub-folders - or at least more than 1 level. From what I've read, it should probably stop the iterations at some point to prevent erroring out or hanging. In practice, I'd be content to go no more than say 5 sub-folders down under each folder of the currently selected parent.
I've found many examples of recursive folder navigation in a variety of scripting flavors but can't understand how to apply any to my ends. There seem to be many different ways to do this. Ironically, the multitude of approaches only adds to my confusion Plus, after a certain age, recursion becomes incomprehensible and I'm well past that point.
iMac 27″, macOS 14.2