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.
- Initially I tried to use
do shell script [...] with administrator privileges
- This didn't work, I believe due to sandboxing,
osascript
the shell commands could read from my Desktop directory when run as me, but were blocked when run as administrator.
- This didn't work, I believe due to sandboxing,
- I tried to use the
copy
command, but quickly found that it's NOT for copying files. This is confusing, many solutions are still using it. - I'm reading that
duplicate
is likely the keyword I should be focusing on but I'm struggling with usingPOSIX file
and when usingalias
.
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...
... and the one-liner:
Some important distinctions from failed attempts:
My Special App.app
). You must copy into theMy Special App.app/Contents
instead.file
andfolder
as they're provided to theduplicate
command.duplicate
call inignoring application responses
[...]end ignoring
to speed up testing which results in timeouts.to
after the application name.