如何使用 AppleScript 删除旧文件(最新文件除外)?

How do I delete old files, except the newest using AppleScript?

我有这个从 a MacRumors forum post 获得的脚本,它会删除文件夹中的所有旧文件:

-- Deletes all old files in Silversions folder, except the newest one.


set modDate to (15)

tell application "System Events"
    set currentUser to (name of current user)
end tell

tell application "Finder"
    try
        delete (entire contents in folder "Silversions" of folder "From Unimportant Source" of folder "Documents" of folder "Libraries" of folder "Google Drive" of folder currentUser of folder "Users" of startup disk whose modification date is less than ((current date)) - modDate * days)
    end try
end tell

将我从特定自动电子邮件中获得的附件放入此文件夹。理论上,这些将不断填充文件夹,我将始终以最新的 15 天的文件结束。但是,如果由于某种原因附件没有成功下载,我想保证文件夹中至少有一个文件,这将是最近获得的文件。

如何修改此脚本以将最新文件保留在文件夹中?

这是执行此操作的流程。它基本上重复主文件夹中的每个文件,检查其修改日期,如果更新,则存储它并删除以前的最新文件,否则删除该文件。

-- Deletes all old files in Silversions folder, except the newest one.

tell application "System Events"
    set currentUser to (name of current user)
end tell

tell application "Finder"
    set theContainer to folder "Silversions" of folder "From Unimportant Source" of folder "Documents" of folder "Libraries" of folder "Google Drive" of folder currentUser of folder "Users" of startup disk

    set newestFile to missing value
    set newestDate to date "Monday, January 1, 1900 at 12:00:00 AM"
    set deleteCount to 0
    set fileList to files of theContainer
    repeat with thisFile in fileList
        set thisDate to (modification date of thisFile)
        -- display dialog ("Newest: " & newestDate as string) & return & "This: " & thisDate as string
        if thisDate > newestDate then
            try
                delete newestFile
                set deleteCount to deleteCount + 1
            end try
            set newestFile to thisFile
            set newestDate to (modification date of newestFile)
        else
            delete thisFile
            set deleteCount to deleteCount + 1
        end if
    end repeat
end tell

display dialog "Deleted " & deleteCount & " files, and kept:" & return & (newestFile as string)

我想到了一种完全不同的方法来完成此操作,使用 OS X 10.4 中引入的一个小功能,即 Finder 的排序命令。 这在技术上更快。

-- Deletes all old files in Silversions folder, except the newest one.

tell application "System Events"
    set currentUser to (name of current user)
end tell

tell application "Finder"
    set theContainer to folder "Silversions" of folder "From Unimportant Source" of folder "Documents" of folder "Libraries" of folder "Google Drive" of folder currentUser of folder "Users" of startup disk
        set sortedList to sort (get files of theContainer) by modification date

    set keepName to name of (item -1 of sortedList)
    delete (every file in theContainer whose name is not keepName)
end tell
display dialog "Kept file: " & keepName