AppleScript to shorten filenames

Hi all,

Bit of a novice here. I played around with Applescript a bit years ago, but have forgotten pretty much all but the basics. I’m working a digital content team who are having issues with using filenames that end up getting rejected by the server their using, usually because the filenames are either too long or contain special characters. We’ve managed to create a script that successfully replaces special characters with underscores, but struggling with getting something to work that shortens the file names.

I found this post on MacScripter which I think with a bit of tweaking would get me close to what we need:

However, I get an error when I try to run it that states: Finder got an error: Can’t set displayed name of file (item 1 of {alias “Macintosh HD:Users:Admin:Library:Mobile Documents:com~apple~CloudDocs:Filename Test:7777777.webp”}) to “1.webp”. (-10006)

Am I right in thinking this is an APFS issue? Any ideas on how to fix it?

Thanks in advance.

Worth noting that I’ve adjusted the max_char value of the script in the linked post from 27 to 5 just for testing purposes. Hence the ‘7777777’ being an invalid filename, but ‘1’ should be fine.

dashed. You are receiving that error message because ‘displayed name’ is read only. I’ve included a suggestion below, which uses ‘name’ instead. The script contains some error correction in the event the user does not include the file extension, although you might want to handle this differently.

property max_char : 5 -- set value as desired

set theItems to (choose file with multiple selections allowed) -- choose file is just for testing

repeat with thisItem in theItems
	tell application "Finder"
		set itemName to name of thisItem
		set extName to name extension of thisItem
		set charCounts to count of characters of itemName
		set extCounts to (count of character of extName) + 1
		if charCounts - extCounts > max_char then
			set newItemName to text returned of (display dialog "This name is too long. Please shorten." default answer itemName)
			if newItemName does not end with ("." & extName) then set newItemName to newItemName & "." & extName
			set name of thisItem to newItemName -- thisItem is an alias
		end if
	end tell
end repeat

Hi peavine, thanks so much! That works perfectly.

Really appreciate your help.