Make/Open Folder

I use these subroutines in many scripts.

The first is trivial. It creates a new folder if none exists or opens the existing folder. In addition to returning the folder id, it returns the exists_flag so that the calling program can react appropriately.

The second creates a new folder. If the name is already in use the new folder’s name has a count suffix added.

on set_save_folder(destination_folder, folder_name, exists_flag)
	tell application "System Events" to set exists_flag to exists folder folder_name in folder destination_folder
	if exists_flag then
		set save_folder to destination_folder & folder_name & ":"
	else
		tell application "Finder" to set save_folder to (make new folder at destination_folder with properties {name:folder_name}) as string
	end if
	return save_folder
end set_save_folder

on make_new_folder(destination_folder, folder_name)
	tell application "System Events"
		set duplicate_count to 1
		set working_name to folder_name
		repeat while exists folder working_name in folder destination_folder
			set duplicate_count to duplicate_count + 1
			set working_name to folder_name & " - " & duplicate_count
		end repeat
	end tell
	tell application "Finder" to set save_folder to (make new folder at destination_folder with properties {name:working_name}) as string
	return save_folder
end make_new_folder