How to change a folder icon ?

Nigel. I tested your rewrite of my script and found two issues, both of which caused the script to fail with an error message. I made the following changes, after which the script worked as expected:

--change this line (the variable |⌘| is not defined)
set searchOptions to (|⌘|'s NSDirectoryEnumerationSkipsPackageDescendants) + (get |⌘|'s NSDirectoryEnumerationSkipsHiddenFiles)
--to this
set searchOptions to (current application's NSDirectoryEnumerationSkipsPackageDescendants) + (get current application's NSDirectoryEnumerationSkipsHiddenFiles)

--change this line (the variable topFolder is not defined)
set entireContents to (fileManager's enumeratorAtURL:(topFolder) includingPropertiesForKeys:(folderAndPackageKeys) options:(searchOptions) errorHandler:(missing value))'s allObjects()
--to this
set entireContents to (fileManager's enumeratorAtURL:(theFolder) includingPropertiesForKeys:(folderAndPackageKeys) options:(searchOptions) errorHandler:(missing value))'s allObjects()

BTW, my script contained an error in testing for the allowed number of subfolders. I’ve fixed that.

Thanks peavine. I should have checked that the script that still actually worked. I’ve now corrected it above and incorporated your change regarding the subfolder count.

The original title of this thread is simply How to change a folder icon? FWIW, I’ve included below a script that works on folders (and files) selected in a Finder window and prompts the user to select the image file to apply to these folders.

use framework "AppKit"
use framework "Foundation"
use scripting additions

tell application "Finder" to set theItems to selection as alias list
if (count theItems) is 0 then display dialog "One or more files or folders must be selected in a Finder window" buttons {"OK"} cancel button 1 default button 1

set iconTypes to {"PNG", "ICNS", "JPG", "JPEG"} --set to desired icon file types
set iconFolder to (path to home folder) --set to desired path to icons
set iconFile to (choose file with prompt "Select an image file to use as an icon:" of type iconTypes default location iconFolder)
set iconImage to current application's NSImage's alloc()'s initWithContentsOfFile:(POSIX path of iconFile)

repeat with anItem in theItems --change icons
	(current application's NSWorkspace's sharedWorkspace()'s setIcon:iconImage forFile:(POSIX path of anItem) options:2)
end repeat

tell application "Finder" to tell window 1 --reset Finder window to see icon changes
	set currentFolder to target
	set target to path to public folder --set to whatever is desired
	try
		set target to currentFolder
	end try
end tell