AppleScript - 获取文件夹中唯一文件的名称?

时间:2017-03-04 18:30:22

标签: macos file applescript directory getfiles

以下AppleScript代码获取最后添加的文件

tell application "Finder"
    set latestFile to item 1 of (sort (get files of (path to downloads folder)) by creation date) as alias
    set fileName to latestFile's name
end tell

来源: How to get the latest downloaded file name with applescript programatically?

但如果文件夹只有一个文件,则会失败。如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

该脚本应该与一个文件一起使用。但如果有没有文件,则会引发错误。

您可以使用try

忽略错误
tell application "Finder"
    try
        set latestFile to item 1 of (sort (get document files of (path to downloads folder)) by creation date) as alias
        set fileName to latestFile's name
    end try
end tell