AppleScript ⇢ Working with Files and Folders

Deleting items older than a given number of days in a given directory.

----------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2018/03/24 13:00
# dMod: 2018/03/24 13:06
# Appl: Finder, System Events
# Task: Trash items from a directory that are older than a given number of days.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Finder, @System_Events, @Trash, @Delete, @Items, @Directory, @Older, @Days
----------------------------------------------------------------

set sourceFolder to alias ((path to home folder as text) & "test_directory:Test_Delete_by_Time:")
set obsoleteDate to (current date)
set time of obsoleteDate to 0 --> changing the time to Midnight
set obsoleteDate to obsoleteDate - (31 * days)

tell application "System Events"
   set itemList to items of sourceFolder whose creation date is less than obsoleteDate
   repeat with i in itemList
      set contents of i to (path of i) as alias
   end repeat
end tell

tell application "Finder" to delete itemList

----------------------------------------------------------------

NOTE – The path to the source directory is an alias – NOT a POSIX Path.

See Putting Relative-Aliases on the Clipboard for how to create an alias with a Keyboard Maestro macro.

-Chris

4 Likes