Copy file to protected directory using AppleScript

applescriptbashfinderterminalzsh

I'm trying to simulate Finder's file copy, but to a protected directory, using AppleScript. The goal is to copy a single file but elevate when needed, like Finder will behave when doing it manually.

An example of a test without elevation:

set posixSrc to (POSIX file "/Users/darwin/Desktop/test.txt") as alias
set posixDst to (POSIX file "/Users/darwin/Desktop/test2.txt") as alias

tell application "Finder"
    duplicate posixSrc to posixDst
end tell

An example of a test with elevation:

set posixSrc to (POSIX file "/Users/darwin/Desktop/test.txt") as alias
set posixDst to (POSIX file "/Applications/My Special App.app") as alias

tell application "Finder"
    duplicate posixSrc to posixDst
end tell

Unfortunately, between POSIX and alias, I'm struggling to figure it all out. Some errors I receive:

error "Finder got an error: Handler can’t handle objects of this class." number -10010

error "Can’t make \"/Users/darwin/Desktop/test2.txt\" into type alias." number -1700 from "/Users/darwin/Desktop/test2.txt" to alias

error "Finder got an error: AppleEvent handler failed." number -10000 from file (file "Macintosh HD:Users:darwin:Desktop:test.txt")

error "Finder got an error: AppleEvent timed out." number -1712

I'm currently testing these with Script Editor but a solution in Terminal is welcome as well.

Best Answer

Got it...

tell application "Finder"
    set posixSource to (POSIX file "/Users/darwin/Desktop/test.txt" as alias)
    set posixDest to (POSIX file "/Applications/My Special App.app/Contents/" as alias)
    duplicate file posixSource to folder posixDest with replacing
end tell

... and the one-liner:

tell application "Finder" to duplicate file (POSIX file "/Users/darwin/Desktop/test.txt" as alias) to folder (POSIX file "/Applications/My Special App.app/Contents/" as alias) with replacing

Some important distinctions from failed attempts:

  • You can't alias a file which doesn't yet exist. For destination, use the destination's parent folder instead.
  • You can't copy into the root of an Application bundle (e.g. My Special App.app). You must copy into the My Special App.app/Contents instead.
  • Pay special attention to the keywords file and folder as they're provided to the duplicate command.
  • When a problem occurs, it can deadlock Script Editor. Wrap your duplicate call in ignoring application responses [...] end ignoring to speed up testing which results in timeouts.
  • When converting to a one-liner you'll need to use the keyword to after the application name.