How Do I Write a Macro to Auto Delete Files in a Directory Each Day?

I am wanting to have KM open at the same time each day, and find in a particular directory, any folder or file that is 31 days old (or older) and move to trash and delete it. I’ve looked at some examples here, however, they appear to require my input live. I want these to run each day without my intervention. (I’m using Automator now, but, if there is an error (no folder that is 31 days old) Automator chokes and does nothing, but I still want the trash emptied in the last step.) Will KM do this for me? And… can you point me to searchable instructions or a tutorial that is more detailed for creating such? I’m really wanting to learn if KM will be useful before purchasing, or more complex (I’m not a programmer) than I can handle. Thank you for your time.

Once upon a time I wrote a Perl script that takes a directory name and a number of days as arguments and deletes everything in that directory that old. Which sounds like what you want to do.

Because it used Unix commands to complete the task, there was no need to Empty the Trash. Which takes care of that problem too.

It had a few fancier options (like a safe mode that just listed the files subject to deletion and a file time option to pick among the various timestamps to use).

And it ran on a schedule dictated by cron.

So I’d suggest you approach the problem from Unix rather than macOS.

Hey Otis,

This is pretty easy to do with AppleScript, and it’s safer than using Unix tools – because items are sent to the Trash rather than deleted on the spot.

See this AppleScript:

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

Run with an Execute an AppleScript action.

-Chris

Thank you Chris. This was very helpful! I also appreciate the link to other AppleScript work that you have done, especially the descriptions and explanations. Have a great day! --Otis

1 Like

Yes, KM can do this for you, and without using or writing any scripts.
While KM easily handles many differents script languages, they are really for more advanced, complicated usage. There are many, many workflows you can automate with KM without ever touching a script.

KM also has many Triggers (KM Wiki). This link is to the KM Wiki, which is very comprehensive and very detailed. You can always access it from the KM Editor Help menu, and from the Help item in the Gear of each Action:

image

The Trigger you most likely will be interested in is the Time of Day trigger. It looks like this:

image

The example macro I uploaded below does NOT have any triggers set. I do this so people who download it are not surprised by the macro being triggered/executed when they don't expect. Of course, it is very easy to add one or more triggers.

Also, I know you asked for the files to be permanently deleted, but while I provide that as an option, the default is to move the files to trash, for safety. But it is very easy to switch to deletion:

  • ENABLE one of these Actions:
    . (be sure to disable the other action)
    . (click the Gear menu to enable/disable any action)

image

KM has many, many Actions that can be combined in many different ways to automate almost any workflow. It is pretty easy to use, but can be overwhelming at first just because there are so many choices. Be sure to go through these Getting Started steps, a remember you can always ask any KM related question here in the forum. It is one of the friendliest and most helpful forums I have ever belonged to.

Getting Started with Keyboard Maestro

  • Read the Quick Start.
    • This is essential to become familiar with KM terminology
  • Do the tutorial (Help ➤ Tutorial) in the KM Editor.
    • Gives you a live walkthrough of creating a macro in the KM Editor
  • Review/Browse the Available Macro Actions
  • For Help with an Action in your Macro, click on the gear icon at the top right of the Action, and select "Help"
  • Search the Keyboard Maestro Wiki for detailed help.
  • Start small, and grow your macros organically.
  • Be prepared for some trial and error in the beginning.
  • Make good use of this Keyboard Maestro Forum
    • Search for existing macros
    • Post your questions/issues if you get stuck

MACRO:   Delete Items in Folder Older Than N Days [Example]


#### DOWNLOAD:
<a class="attachment" href="/uploads/default/original/3X/b/0/b057c95b83f5eaccc1441257122381a98adaef97.kmmacros">Delete Items in Folder Older Than N Days [Example].kmmacros</a> (72 KB)
**Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.**

Please feel free to post any questions, issues, and/or suggestions.

---

### Example Output

![image|577x346](upload://abW6b5vXwxWImjVvlZodNZRW3T1.png)

---

### ReleaseNotes

Author.@JMichaelTX

**PURPOSE:**

* **Delete or Move to Trash Items in Folder Older than N Days**
   * By default, it uses Move to Trash, but you can disable this and enable the Delete Action.

**REQUIRES:**

1. **KM 8.2+**
  * But it can be written in KM 7.3.1+
  * It is KM8 specific just because some of the Actions have changed to make things simpler, but equivalent Actions are available in KM 7.3.1.
.
2. **macOS 10.11.6 (El Capitan)**
  * KM 8 Requires Yosemite or later, so this macro will probably run on Yosemite, but I make no guarantees.  :wink: 

**NOTICE: This macro/script is just an _Example_**

* It has had very limited testing.
* You need to test further before using in a production environment.
* It does not have extensive error checking/handling.
* It may not be complete.  It is provided as an example to show you one approach to solving a problem.

**How To Use**

1. Trigger this macro.
   * There are many choices for 
   * Once choice is the  [Time of Day trigger](https://wiki.keyboardmaestro.com/trigger/Time_of_Day).  It looks like this:
.
![image|391x119](upload://pC3YMHpF8hL0y7zvyyIbYwDVZgn.png)

  * It will then execute without any prompting, but will display the results at the end. 
   * Of course, you can disable or change this display.

**MACRO SETUP**

* **Carefully review the Release Notes and the Macro Actions**
  * Make sure you understand what the Macro will do.  
  * You are responsible for running the Macro, not me.  ??
.
1. Assign a Trigger to this maro..
2. Move this macro to a Macro Group that is only Active when you need this Macro.
3. ENABLE this Macro.
.
* **REVIEW/CHANGE THE FOLLOWING MACRO ACTIONS:**
(all shown in the magenta color)
   * Set Variable “DIF__DeleteOlderThanDays” to Text “31”
   * Set Variable “DIF__SourceFolderPath” to Text “~/Documents/TEST/KM-Test-For-Deletion”
   * ENABLE one of these Actions:
. (be sure to disable the other action)
.
     * Trash -- Item will be moved to macOS Trash
     * Delete -- Item will be permanetly deleted

TAGS: @Files @ForEach @Trash @Delete @Time @Example

USER SETTINGS:

* Any Action in _magenta color_ is designed to be changed by end-user

ACTION COLOR CODES

* To facilitate the reading, customizing, and maintenance of this macro,
      key Actions are colored as follows:
* GREEN   -- Key Comments designed to highlight main sections of macro
* MAGENTA -- Actions designed to be customized by user
* YELLOW  -- Primary Actions (usually the main purpose of the macro)
* ORANGE  -- Actions that permanently destroy Variables or Clipboards,
OR IF/THEN and PAUSE Actions


**USE AT YOUR OWN RISK**

* While I have given this limited testing, and to the best of my knowledge will do no harm, I cannot guarantee it.
* If you have any doubts or questions:
  * **Ask first**
  * Turn on the KM Debugger from the KM Status Menu, and step through the macro, making sure you understand what it is doing with each Action.

---

![image|275x2000](upload://1XjRDBE2w603FoGKiFBW4CQFQjw.png)
3 Likes

@omamed, as I mentioned in the Macro Comments, you can view (and even edit) the KM Variables you used as they were set by the last execution of your Macro.

So this will let you view the last log of files deleted anytime you want.

Goto KM Editor > Preferences > Variables

image

@omamed, I hope you don’t mind that I have revised your topic title to better reflect the question you have asked.

FROM:
Noob query… Trying KM… maybe not for me

TO:
How Do I Write a Macro to Auto Delete Files in a Directory Each Day?

This will greatly help you attract more experienced users to help solve your problem, and will help future readers find your question, and the solution.

@omamed,
I preface this with saying that KM is one of the most valuable apps that I own. Useful in so many diverse areas. I would recommend all serious Mac users buy and learn it (at least at a basic level).

For the specific task that you are trying to accomplish, if you find the KM solution “too complicated”, you might find the app Hazel easier to understand in its ability to achieve the same goal. KM is vastly more powerful in the domain of automation problems to solve than is Hazel which essentially covers a small subset of what KM can do. But in that subset (folder automations), Hazel probably would feel easier.

@JMichaelTX, Thank you so much for your effort here. I am taking my time to understand it all and learn from your examples and discussion. This is the help I was looking for. So amazed at the support from you! I will eventually report back here on my success (I’m sure I will be!) as soon as I can take the time to understand and implement… cautiously. Again, many thanks! --Otis

1 Like

@rlivingston, Thank you for your response in support of KM. I like the level of possibilities and control that KM seems to offer over Hazel. Though, if I find myself overwhelmed with KM, I may give that a try. Again, thank you for your feedback! --Otis

JMichaelTX , I have been using the script you provided, with a couple of minor changes, and it has been working for me for months. My need to delete "files" has changed to the need to delete "folders" (directories) instead. I duplicated your original script, set the path to the folder where the folders are, however, it seems not to want to move them to the trash as they are "directories". I found where the "files" in the directory are selected, but nothing in that list of options allows for "directories" to be selected instead. How would I do that? If I can attach a snapshot of what I am looking at, I will after sending this message. Thanks for any help from the forum members!

51%20AM

I don't immediately see a method using native KM Actions to delete folders, but this can be easily done with an AppleScript. I don't have time right now to look at this, but will try later. Perhaps another forum member (like Chris @ccstone) already has such a script they can share.

If you don't hear from me or someone else within a day or so, feel free to ping me in this thread.

Hey Otis,

Keyboard Maestro actions won't delete folders (for safety), so you have to resort to either the shell or AppleScript.

The AppleScript for this is pretty simple.

You can move folder to the trash or immediately delete them.

# Requires full POSIX Path or Tilde-Based-POSIX Path
set targetFolderPath to "~/Downloads/Test Folder/"

tell application "System Events"
   set targetFolder to disk item targetFolderPath
   
   # Move Folders of Target Folder to Trash (safer).
   move (get folders of targetFolder) to trash
   
   # Immediate Deletion of Folders of Target Folder.
   # delete folders of targetFolder
   
end tell

I generally prefer to move items to the trash instead of immediately deleting them, so I have the means to recover if I goof somewhere.

This job can be done with a shell script, but using AppleScript is easier and safer.

-Chris

Chris, what if you want to move everything, folders and files, to the trash?

Hey JM,

Change “folders” to “items” like so:

# Requires full POSIX Path or Tilde-Based-POSIX Path
set targetFolderPath to "~/Downloads/Test Folder/"

tell application "System Events"
   set targetFolder to disk item targetFolderPath
   
   # Move Folders of Target Folder to Trash (safer).
   move (get items of targetFolder) to trash
   
   # Immediate Deletion of Folders of Target Folder.
   # delete folders of targetFolder
   
end tell

By changing “items” to “files” you can limit it to files-only.

-Chris

1 Like

JMichaelTX and ccstone , Thank you for your responses. I can certainly do the script, based on your example Chris. I can see why KM would not want to do the directory delete for safety reasons. I just wanted to be sure that I was not blind to how to do it with KM as I am still just a noob at it.

I too prefer the move to trash vs the delete immediately, at least until I have several successful operations of the script running without a hitch.

Again, thank you to you both, for the support provided here in the community. I'll work this up and give it a whirl. Happy Holidays! --Otis

1 Like

This is awesome J-Mike! Really great for learning about variables and such as well as KM operation. TY TY

Hey There,

I'm sad to say that @JMichaelTX will never see your thanks...

The Passing of JMichaelTX

JMichaelTX – Unforgettable Generosity With His Time and Knowledge

Take Care,
Chris

(Keyboard Maestro Moderator)

1 Like