0

У меня есть этот сценарий, который я получил от a MacRumors forum post, который удаляет все старые файлы в папке:Как удалить старые файлы, кроме новейших, используя AppleScript?

-- 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 дней. Однако, если вложения не были успешно загружены по какой-либо причине, Я хочу гарантировать, что хотя бы один файл остается в папке,, который был бы последним полученным.

Как изменить этот скрипт, чтобы оставить последний файл в папке?

ответ

2

Я думал совершенно иначе, чтобы достичь этого, используя малоупотребляемую функцию, введенную в 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 
+0

Мне нравится! Очень элегантно! –

0

Вот поток, который сделает это. Он в основном повторяется через каждый файл в основной папке, проверяет дату его модификации и, если его новее, он сохраняет его и удаляет предыдущий новейший файл, в противном случае он удаляет этот файл.

-- 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) 
Смежные вопросы