Codename K
Codename K

Reputation: 744

AppleScript - Get the name of the only file in a folder?

The following AppleScript code gets the file that was added last,

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

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

But this fails if the folder has only one file. How to fix this?

Upvotes: 0

Views: 752

Answers (1)

vadian
vadian

Reputation: 285250

The script is supposed to work with one file. But it throws an error if there is no file.

You can ignore the error with a try block

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

Upvotes: 2

Related Questions