I just completed my first working script. It simply moves all selected files/folders from a Finder window to a folder called “Sundries” in my “Documents” folder, then leaves aliases to those files on the desktop. If a similarly named file/folder is already present in “Sundries”, then the item is renamed successively “original name-1”, “original name-2”, etc, until a unique name is found before moving it.
After much trial and error (three days!!!), I came up with a simple way to refer to a file/folder by its complete path, namely, “item (complete_path & item_name)”. I was especially stumped until I learned that the term “item” was required in the “set name of item …” statement, but was optional or even disallowed in other statements.
I have two questions:
-
Can you kindly explain why “item” is mandatory in “set name of item …”; optional in “move item …” and “make new alias file at desktop to item …”; and not allowed in “alias [item] …”, despite the fact that the construct is the same in each case, namely “item (complete_path & item_name)”.
-
Also, I would be very grateful for any comments on how to make the script more elegantly coded, and whether “item (complete_path & item_name)” is a recommended way to refer to a file/folder by its complete path or if there is a better way.
The script is as follows:
tell application "Finder"
-- "Sundries" is the destination folder of the items to be moved.
set sundries_path to "MacIntosh HD:Users:username:Documents:Sundries:"
set input to get selection
-- Cycle through all the items selected in the Finder window.
repeat with current_item in input
set original_path to (container of current_item) as text
set original_name to name of current_item
set counter to 0
set done to false
set current_name to original_name
repeat while not done
try
-- "alias" command is used as an expedient way to test for the existence of the current item in the "Sundries" folder. If the item doesn't already exist in "Sundries", then execution skips to "on error".
alias (sundries_path & current_name)
-- If the current item already exists in the "Sundries" folder, try appending "-1", "-2", and so on until a unique name is found.
set counter to counter + 1
set new_name to (original_name & "-" & (counter as string))
set name of item (original_path & current_name) to new_name
set current_name to new_name
on error
-- Move the uniquely named item to the "Sundries" folder.
move item (original_path & current_name) to sundries_path
-- Make an alias of the item on the desktop.
make new alias file at desktop to item (sundries_path & current_name)
set done to true
end try
end repeat
end repeat
end tell