使用Apple脚本压缩文件夹

4
我正试图使用AppleScript将文件夹复制到我的桌面,对其进行压缩,然后移动.zip文件到其他地方,但是我无法使压缩部分工作。
我已经搜索了各个地方以找到在AppleScript中压缩文件/文件夹的方法,但我不知道自己哪里错了,因为其中没有一个方法适用于我。
我也不想在复制了文件夹并压缩之后再选择文件夹,但我认为在修复压缩之前最好留下它们。
非常感谢您提供的任何帮助。
这是我的代码:(在得到djbazziewazzie的帮助后更新)
set workspace to (path to desktop as text) --"Users:produser:Desktop"

tell application "Finder"

display dialog "Select a folder to be zipped"
set inputFolder to choose folder
set inputFolderProperties to properties of inputFolder
set inputFolderName to name of inputFolder

duplicate inputFolder to workspace with properties --copy input folder to workspace
{name:inputFolderName} --keep the same name

--set copiedFile to (workspace & inputFolderName) 
display dialog "Select the folders desktop copy"
set copiedFile to choose folder --select the file copy thats on the workspace

tell current application
    set qpp to quoted form of POSIX path of copiedFile
    do shell script "zip -r " & qpp & ".zip " & qpp -- zips the file (or not...)
end tell

display dialog "Select the .zip file" --select the new .zip file
set zipFile to choose file
display dialog "Select the output folder"
set outputFolder to choose folder --moves zipped file
move zipFile to outputFolder

end tell   
1个回答

3

应用程序是目录,因此您需要使用zip的-r选项将文件夹中的所有文件添加到zip文件中。在Mac OS X中,以.app结尾的目录显示为文件而不是文件夹。

另外,在tell application“Finder”内部使用do shell script违反了脚本附加安全策略。只有当目标设置为常量current application时,才应使用do shell script。默认情况下,没有针对应用程序的代码会定位到当前应用程序。

tell current application
 do shell script "zip -r " & qpp & ".zip " & qpp -- zips the file (or not...)
end tell

编辑 1: 展示工作代码

编辑 2: 更新了 do shell script 以使用相对路径

set workspace to (path to desktop as text)

tell application "Finder"
    set inputFolder to choose folder with prompt "Select a folder to be zipped"

    set copiedFile to (duplicate inputFolder to workspace) as string
    set copiedFile to text 1 thru -2 of copiedFile --remove the trailing ":" 

    tell current application
        set qpp to quoted form of POSIX path of copiedFile
        do shell script "cd $(dirname " & qpp & ")
    zip -r  \"$(basename " & qpp & ").zip\" \"$(basename " & qpp & ")\""
        set zipFile to copiedFile & ".zip"
    end tell

    set outputFolder to choose folder with prompt "Select the output folder"
    move zipFile to outputFolder
end tell

谢谢您的回复,根据您的建议我不再收到任何错误消息,但很遗憾它仍然不能压缩所选文件。 - man-qa
1
我已经测试了你的代码并进行了更新,同时编辑了我的帖子。你之前遇到的错误是因为选择文件夹返回的文件夹末尾带有“:”。压缩文件的路径看起来像是“/Users/<user>/Desktop/foldertozip/.zip”。这会导致一个名为“.zip”的隐藏文件,因为以点开头的文件在Finder中是不可见的。所以文件已经被创建,但却出现在了意料之外的地方。 - dj bazzie wazzie
非常感谢您让它工作了,只有一个小问题:当我打开新的.zip文件时,它包含一个用户文件夹、一个用户名文件夹,最后是一个桌面文件夹,直到它到达我选择压缩的文件夹。您知道如何解决这个问题吗? - man-qa
1
Zip 命令使用相对路径来定位工作目录,但是在 do shell 脚本中,默认的当前工作目录是根目录。此外,该脚本不支持相对路径,只能使用绝对路径,因此需要将从根目录到所选文件夹的完整路径存储在 zip 归档文件中。我已经更新了脚本以支持相对路径。 - dj bazzie wazzie
太好了:D非常感谢你,你真是个美丽的人:) - man-qa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接