使用Apple脚本压缩文件夹

时间:2014-04-30 13:14:06

标签: macos shell zip applescript

我正在尝试使用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 个答案:

答案 0 :(得分:2)

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

tell application" Finder" 中使用do shell脚本也违反了脚本添加安全策略。只有在目标设置为常量current application时才能使用shell脚本。默认情况下,每个未定位到应用程序的代码都会定位到当前应用程序

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

编辑1:显示工作代码

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

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