MacOS – Applescript to copy folder (and contents) to current location

applescriptfindermacos

I am trying to create a button on my Finder toolbar powered by applescript to make a copy of a set folder (e.g. /Users/James/doc) and all files/subfolders within it to the current location in Finder.

The motivation for this is that I have a LaTeX documentation format with subfolders such as img that I normally add to every new coding project in a folder called doc, so having a button that adds this folder would save me time instead of manually copying it across each time.

My applescript skills are not very good, I have tried:

1)

set x to ((the target of the front window) as text) as alias
set y to ((folder "Users/James/doc") as text) as alias

tell application "Finder"
    duplicate y to x
end tell

the error I get from running this first attempt is: Can’t make target of window 1 of «script» into type text.

2)

tell application "Finder"
    duplicate folder "Users/James/doc" to (the target of the front window)
end tell

which when run gives the error Finder got an error: Can’t set target of window 1 to folder "Users/James/doc".

(PS: I already know how to turn the applescripts into Finder buttons)

Best Answer

The following script should work:

property y : POSIX file "/Users/James/doc" as alias

tell application "Finder"
    set x to target of window 1 as alias
    duplicate y to x
end tell

By setting y as a property (and as an alias), the script should not break by simply renaming or moving the the folder to be copied.