Proper use of Finder, System Events, repeat

I am trying to replace the names of a selection of files with the contents of the clipboard.

If the selection consists of a single file, the code works fine.


tell application "Finder"
	activate
	tell application "System Events"
		keystroke return
		delay 0.1
		keystroke "v" using command down
		delay 0.1
		keystroke return
	end tell
end tell

However, if the selection consists of several items I get no result.


tell application "Finder"
	activate
	set sel to selection as alias list
	repeat with x in sel
		tell application "System Events"
			keystroke return
			delay 0.1
			keystroke "v" using command down
			delay 0.1
			keystroke return
		end tell
	end repeat
end tell

I would appreciate any help in finding the solution and understanding where I am making the mistake.

Model: iMac
AppleScript: 2.11
Browser: Google Chrome
Operating System: macOS 12

It doesn’t work because the selection is more than one file.
You can’t edit the names of multiple files at the same time.
You would have to iterate thru the list and make sure your selection is only one file at a time.

Also you cant name 2 files to the same name in the same folder (location)

Here is a small script that works
I would also recommend that you not use GUI scripting when an app can do this programmatically.


tell application "Finder"
	activate
	set sel to selection as alias list
	repeat with x from 1 to count of sel
		tell application "Finder"
			set selection to item x of sel
		end tell
		set the clipboard to (the clipboard) & x
		tell application "System Events"
			keystroke return
			delay 0.1
			keystroke "v" using command down
			delay 0.1
			keystroke return
		end tell
	end repeat
end tell

Here is a simply script not using GUI commands


tell application "Finder"
	activate
	set sel to selection as alias list
end tell
set clip to the clipboard
tell application "System Events"
	repeat with x from 1 to count sel
		set ext to name extension of item x of sel
		tell application "System Events"
			set name of item x of sel to clip & x & "." & ext
		end tell
	end repeat
end tell

1 Like

:smiley:
Hello robertfern.

Thank you very much for your quick and effective help.
I have understood your solution and what is the error in my approach.
I keep your advice as something of great value that will be very useful also for other scripts where I have similar problems.

Receive my greetings and my gratitude.