[Apple] Automatically Delete Files From Downloads Folder Daily Unless Tagged With "Keep"?
Automatically Delete Files From Downloads Folder Daily Unless Tagged With “Keep”?
The following example AppleScript code can be used in a shell script with an /usr/bin/osascript
shebang, or an AppleScript script/application, or a Run AppleScript action in an Automator workflow to delete any file in the targetFolder
that does not have a custom "Keep" Tag set in Finder:
-- # targetFolder can be either an HFS path or a POSIX path,
-- # "path:to:target:folder:" or "/path/to/target/folder"
-- #
-- # Change the value of targetFolder from "/path/to/target/folder"
-- # to the appropriate fully qualified pathname in either form.
set targetFolder to "/path/to/target/folder"
-- # The remaining code should not need to be modified,
-- # unless the mdfind query needs to be changed.
set targetFolderPOSIXpath to ¬
the quoted form of ¬
the POSIX path of targetFolder
set shellCMD to {¬
"mdfind -onlyin", space, targetFolderPOSIXpath, space, ¬
"'! kMDItemKind == Folder && ! kMDItemUserTags == Keep'"} ¬
as string
set posixFilesToDelete to ¬
paragraphs of ¬
(do shell script shellCMD)
set filesToDelete to {}
repeat with thisFile in posixFilesToDelete
set thisFile to POSIX file thisFile as alias
set the end of filesToDelete to thisFile
end repeat
if filesToDelete is not {} then ¬
tell application "Finder" to ¬
delete filesToDelete
Note: Scroll as necessary to see remaining code.
Notes:
- As I do not have the target folder mentioned in the OP, I could not test for any permissions issues that may need addressing in: System Preferences > Security & Privacy > Privacy
- The example AppleScript code was tested and work for me without issue in macOS Catalina using a temporary folder created within my Home folder while adding files and folders to it and tagging only some files with a custom "Keep" Tag in Finder.
- As to "Automatically Delete Files" there are a number of different ways to accomplish this depending on how the example AppleScript code is used. Used as an AppleScript shell script or application it can be scheduled to run at whatever time you'd like, using any of several different methods.
- As an AppleScript application using: Calendar
- As an AppleScript shell script using:
launchd
orcron
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.