Adding labels to files in folders on drop

I’m pretty much an Applescript newbie but I’m trying to write a script that will add a certain color label to a file based on its extension. I’m starting simple with just JPG’s but am having problems figuring out what I’m doing wrong:

on open these_files
	tell application "Finder"
		if file type of these_files starts with "JPG" then set label index of these_files to 3
	end tell
end open

on run
	display dialog "Drop files and folders on this icon"
end run

But this gives me the following error when I drag a folder or file over it and it runs:

Can't get <<class asty>> of {alias Macintosh HD: Users: RickB: Pictures: samplepics:}

This folder “samplepics” contains about 15 JPG’s that currently have no labels.

Can someone point me in the right direction?

rberry88

In your script, these_files is a list of files. A list doesn’t have a type, and can’t have a lable, but the individual files contained in the list can have these things. You need to loop through the list and work with one file at a time. this is a common construct for droplettes.

Next issue: In OSX, files may OR MAY NOT have an OST file type. In OS9 and down, files always had one. The file type is not the same thing as the file extension (typically the 3 letters after the . at the end of the file name.)

So…

on open these_files
tell application “Finder”
repeat with theFile in these_files

		set theFileName to the name of theFile
		set theFileType to (characters -4 through -1 of theFileName) as string
		if theFileType is ".jpg" then set label index of theFile to 3
		
		-- This line is not needed but doesn't hurt either...
		if file type of theFile starts with "JPG" then set label index of theFile to 3
		
	end repeat
end tell

end open

on run
display dialog “Drop files and folders on this icon”
end run

Note that this script has two if statements – it’s looking at both the extension and the file type. In practice, jpg file names almost always end with .jpg, so you don’t need the second if statement.

Hmm, wow. Thanks for the help as it was extremely helpful.

The only problem I’m running into is that it won’t accept folders of items, it will only accept individual items dropped on it one by one. Sometimes I’ll have a folder of about 100 files and want an easy way to distinguish the JPG’s from GIF’s, Mov’s etc, so it would be more helpful to have it accept folders too.

rberry88