Using applescript I want to move a file that is selected in the Finder to another folder and also change the name of the file being moved.
This is what I’ve got so far. It seems to work but also seems very clumsy. Is there a better way of doing it please?
tell application "Finder"
set itemlist to the selection
set theFile to item 1 of itemlist
set name of theFile to "zmoved.txt"
set itemlist to the selection
set theFile to item 1 of itemlist
set thePath to desktop
move theFile to desktop
end tell
Model: Macbook Pro
AppleScript: 2.5
Browser: Safari 603.2.5
Operating System: Mac OS X (10.11.6)
The problem you’ve found is that the Finder’s references to folders and files are name references. When you change the name of the item referred to by ‘theFile’, the reference in the variable still has the old name, so you have to go back to the selection and get another reference with the new name.
One way round this is to coerce the original reference to an alias. This will keep track of the file after it’s renamed or moved:
tell application "Finder"
set itemlist to the selection
set theFile to (item 1 of itemlist) as alias
set name of theFile to "zmoved.txt"
move theFile to desktop
end tell
Another possibility would be to move the file first. The Finder’s ‘move’ command returns a reference to the item in the new location, so you could use that when renaming the file.
tell application "Finder"
set itemlist to the selection
set theFile to item 1 of itemlist
set theFile to (move theFile to desktop)
set name of theFile to "zmoved.txt"
end tell
Or you could use some combination of approaches, of course, depending on what else the script had to do. Any method will throw an error if an item with the same name already exists in the same folder at any stage.