AppleScript中的系统事件是否支持重复文件?

时间:2012-11-07 04:26:27

标签: applescript

我一直在尝试让系统事件在AppleScript中复制文件而且我一直在失败:)我最终总是得到错误“错误”文件无法复制。“编号-1717”。所以我改变了我的策略并尝试使用Finder来确保我尝试做的事情是正确的。以下是有效的代码:

告诉应用程序“系统事件”

set desktopFolder to (path to desktop folder) as string
set fullPath to desktopFolder & "Temp Export From DO"

set theDOEntries to every file of folder "/Users/jkratz/Dropbox/Apps/Day One/Journal.dayone/entries" whose name extension is "doentry"
repeat with DOEntry in theDOEntries
    set source to path of DOEntry
    log "Source file: " & source
    set destination to fullPath as string
    log "Destination folder: " & destination
    tell application "Finder"
        duplicate file source to folder destination with replacing
    end tell
end repeat

告诉

如果我删除了最后一个告诉,以便它使用系统事件,我会得到上面提到的相同错误。 System Events标准套件的字典有一个“重复”命令,所以我不确定这里发生了什么。此外,来自APress的“学习AppleScript,第3版”注:

“系统事件中一个特别恼人的遗漏是它无法复制文件和文件夹;如果你需要这样做,Finder是你最好的选择。”

第3版是从2010年开始。即使在Mountain Lion,这似乎仍然是真的。谁能证实这一点? 1717错误号列在其他地方作为处理程序错误,我没有使用处理程序。

2 个答案:

答案 0 :(得分:1)

不幸的是,您无法使用系统事件复制文件 - 您必须使用Finder。即使在adayzdone提供的答案中,系统事件实际上并没有处理重复。

这看起来很有效(因为它在系统事件告诉块中)...

tell application "System Events"
    duplicate myFile to myFolder
end tell

...但是如果你检查事件日志,你会发现Finder实际上正在执行复制。在幕后,您将两个Finder对象传递给系统事件。系统事件不知道如何处理Finder对象,因此执行被传递给对象'所有者,Finder,执行命令。

对于AppleScript中的文件复制,遗憾的是,您只能通过do shell script使用Finder或命令行。

答案 1 :(得分:0)

尝试:

tell application "Finder" to set desktopFolder to (path to desktop folder as text) & "Temp Export From DO" as alias
tell application "System Events" to set theDOEntries to every file of folder "/Users/jkratz/Dropbox/Apps/Day One/Journal.dayone/entries" whose name extension is "doentry"
repeat with DOEntry in theDOEntries
    log "Source file: " & DOEntry
    log "Destination folder: " & desktopFolder
    tell application "Finder" to duplicate file DOEntry to desktopFolder with replacing
end repeat

如果您不需要记录值,您可以简单地:

tell application "Finder" to set desktopFolder to (path to desktop folder as text) & "Temp Export From DO" as alias
tell application "System Events" to set theDOEntries to every file of folder "/Users/jkratz/Dropbox/Apps/Day One/Journal.dayone/entries" whose name extension is "doentry"
tell application "Finder" to duplicate theDOEntries to desktopFolder with replacing

或者:

set desktopFolder to quoted form of (POSIX path of (path to desktop folder as text) & "Temp Export From DO")
do shell script "find '/Users/jkratz/Dropbox/Apps/Day One/Journal.dayone/entries' -name \"*.doentry\" -type f -print0 | xargs -0 -I {} cp -a {} " & desktopFolder

回到您的问题,重复的命令会创建Finder项目的副本。您可以使用系统事件来复制Finder项目,如下所示:

tell application "Finder"
    set myFile to file ((path to desktop as text) & "Test File.txt")
    set myFolder to folder ((path to desktop as text) & "Test Folder")
end tell

tell application "System Events"
    duplicate myFile to myFolder
end tell