Get every folder in a given folder

Hi,
I don’t really grasp the semantics of some operations targeted at the Finder. I hope someone would be so kind to enlighten me :slight_smile: In particular, the following script results in a list of all the folders contained in the Downloads folder if there are any, but it produces an error if the the Downloads folder is empty:


tell application "Finder"
	every folder of (entire contents of folder (path to downloads folder))
end tell

Can someone tell me why in the latter case the result is not the empty list but the error “Can’t get every folder of folder “Downloads” of [.]”? Also, is this the fastest way (do shell script aside) to get a list of folders within a given folder?

Hi,

entire contents throws an error if its container is empty.
You can catch the error this way


set downloadsFolder to (path to downloads folder)
tell application "Finder"
	try
		set folderList to every folder of (entire contents of downloadsFolder)
	on error
		set folderList to {}
	end try
end tell

Note: as path to downloads folder represents an alias, remove the keyword folder.
I also recommend to avoid any Scripting Addition command within an application tell block (if possible)

Thanks for your reply!

Ok, so this is expected behaviour. Just I cannot find where it is documented.

Do you refer to path to in the above example? Could you elaborate on why this is advisable?

I don’t know, whether this is the expected behaviour, indeed this is the behaviour

It could cause terminology clahes, for example Mail.app “translates” path to into for rule or something similar. Even Apple recommends to avoid Scripting Additions commands within application tell blocks

Entire contents actually does produce an empty list, but there are three operations in that line, the third of which is a get folders. The empty list was already realized prior to that, and there are no folders in an empty list.

To be exact, it’s the extended reference every of (entire contents .) which errors if that particular kind of element doesn’t exist in the folder.

Perversely, a filter does work both in either case:


tell application "Finder"
	every item of (entire contents of folder (path to downloads folder)) whose class is folder
end tell

If you’re looking for files by this method, though, you have to be specific about the class(es) of file (ie. document file, application file, etc.)

Interesting, I’ve never thought about it. I’ll keep it in mind.

I see. That starts to make sense to me.


Indeed. entire contents alone does return an empty list.

Is AppleScript surprising, or what? :slight_smile: In my tests, though, using a filter is about 10 times slower than using every folder of (entire contents of.)