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

I have this script that I got from a MacRumors forum post, which deletes all old files in a folder:
-- 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
Into this folder go attachments I get from particular automated emails. In theory, these will continually populate the folder, and I will always end up with the latest 15 days-worth of files. However, if the attachments are not successfully downloaded for some reason, I want to guarantee at least one file stays in the folder, which would be the most recently-gotten one.
How would I amend this script to leave the latest file in the folder?

I thought of a completely different way to accomplish this, using a little used feature introduced in OS X 10.4, Finder's sort command.
This is technically quicker.
-- 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

Here's a flow that would do this. It basically repeats through every file in the main folder, checking its modification date, and if its newer, it stores it and deletes the previous newest file, otherwise it deletes that file.
-- 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)

Related

Deleting all files in a selection of folders using applescript

I currently have a script that deletes all files in a particular file path, that are 14 days old:
tell application "Finder"
delete (every file of folder "client" of folder "test" of folder "Dev, Con & Product" of folder "Google Drive" of folder (path to home folder) whose creation date is less than ((get current date) - 14 * days))
end tell
I am struggling to adapt this script so that instead of looking in the "client" folder and deleting all files, it looks in the "client 1", "client 2", "client 3" folders etc. and deletes all files that are 14 days old.
Any help on this would be great,
Thanks
Assuming that client 1 , client 2,...folders are still in same path (in folder "Dev, Con & Product", then keep current script, just changing "client" to "client 1"
if you have some many client folder, then you must use a repeat loop instead :
set myParent to (((path to home folder) as string) & "Google Drive:Dev, Con & Product:test") as alias
tell application "Finder"
set Myfolders to every folder of folder myParent whose name contains "Client"
repeat with OneFolder in Myfolders
delete (every file of OneFolder whose creation date is less than ((get current date) - 14 * days))
end repeat
end tell

Trouble with script moving files to a newly created folder in Applescript

I am having trouble with what I think is a pretty straightforward task, but cannot seem to get my script to work correctly. I have found a lot of help through the forums with regards to the individual routines used, but it still seems to fail.
In short, what I would like to do is monitor a folder for new files being added. Once a batch of files are added (every other day or so), it will create a folder in another directory with the new folder name being the current date, move those files to the new directory, and then execute a simple bash script which uses the new directory name as an argument.
My script compiles ok, but once files are added it only creates the new folder and nothing else. I appreciate any help.
property the_sep : "-"
on adding folder items to my_folder after receiving the_files
tell application "Finder"
(* First create a new folder with name of folder = current date *)
set the_path to (folder "qa" of folder "Documents" of folder "ehmlab" of folder "Users" of disk "Macintosh HD")
set the_name to (item 1 of my myDate())
set the_name to (the_name & the_sep & item 2 of my myDate())
set the_name to (the_name & the_sep & item 3 of my myDate())
make folder at the_path with properties {name:the_name}
set newDir to the_path & the_name
end tell
(* Next, move the newly added files to the source into the newly created date folder *)
repeat with i from 1 to number of items in the_files
tell application "Finder"
try
set this_file to (item i of the_files)
move file this_file to folder newDir
end try
end tell
end repeat
do shell script "qc.sh " & newDir
end adding folder items to
on myDate()
set myYear to "" & year of (current date)
set myMth to text -2 thru -1 of ("0" & (month of (current date)) * 1)
set myDay to text -2 thru -1 of ("0" & day of (current date))
return {myYear, myMth, myDay}
end myDate
The failure reason are different path styles.
AppleScript uses HFS paths (colon separated).
UNIX uses POSIX paths (slash separated).
The solution is to coerce the HFS path string to POSIX path
do shell script "qc.sh " & quoted form of POSIX path of newDir
This is a shorter version of the script using the shell also for the time stamp and for creating the directory.
on adding folder items to my_folder after receiving the_files
(* Next, move the newly added files to the source into the newly created date folder,
"path to documents" is a relative path to the documents folder of the current user *)
set baseFolder to (path to documents folder as text) & "qa:"
set timeStamp to do shell script "date +%Y-%m-%d"
set newDir to baseFolder & timeStamp
do shell script "mkdir -p " & quoted form of POSIX path of newDir
(* Next, move the newly added files to the source into the newly created date folder *)
repeat with aFile in the_files
tell application "Finder"
try
move aFile to folder newDir
end try
end tell
end repeat
do shell script "qc.sh " & quoted form of POSIX path of newDir
end adding folder items to

Moving a file into a folder with Applescript

I'm fairly new to learning applescript, and I'm trying to set up something for my school's announcement system in order to make it more automated. This is supposed to take the current date, check if a folder for the month exists, and if it doesn't- create one. Then it should move the announcement file into that folder.
For some reason, this worked fine until a folder was added to the desktop containing all the other folders (I don't know why, but this is quite normal for my school). Anyway, I had to edit the file path and now its not working properly. Any help would be appreciated.
property parentFolder : ((path to desktop folder) & "DESKTOP_NEWS")
on run argv
set myFile to item 1 of argv
set myMonth to month of (current date)
set currentMonthFolder to myMonth & space & "Announcements" as text
tell application "Finder"
if not (exists folder currentMonthFolder of parentFolder) is true then
make new folder at parentFolder with properties {name:currentMonthFolder}
end if
move myFile to folder currentMonthFolder of parentFolder
end tell
end run
I just tested this ( except the move part ) and it works as expected. Mainly the parent_folder was created wrongly.
property parentFolder : (((path to desktop folder) as text) & "DESKTOP_NEWS" as alias)
on run argv
set myFile to item 1 of argv
set myMonth to month of (current date)
set currentMonthFolder to (myMonth & space & "Announcements") as text
tell application "Finder"
if not (exists folder currentMonthFolder of parentFolder) then
make new folder at parentFolder with properties {name:currentMonthFolder}
end if
move myFile to folder currentMonthFolder of parentFolder
end tell
end run

Applescript - move files to folder which name begins with first 7 characters of filename

I've got 2 folders
the first folder contains all the files which I'd like to move to a subfolder of the second folder. I'd like to this based on the first 7 characters of both the file & folder names.
So if the first 7 characters of the subfolder in FOLDER 2 matches the first 7 characters of the file in FOLDER 1. The file get's moved into the subfolder of FOLDER 2
Right now I've got an Applescript which works, but it's terribly slow.
Here's the script so far:
set mgFileList to ""
set mgDestFolder to ""
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
set folderList to contents of mgDestFolder
tell application "Finder" to set fileList to files of mgFilesFolder
repeat with aFile in fileList
set prefix to getPrefix(name of aFile)
tell application "Finder"
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to destinationFolder
end try
end tell
end repeat
on getPrefix(aName)
set prefix to text 1 thru 7 of aName
return prefix
end getPrefix
I've only recently got into Applescripting. Can this be done more efficiently within Applescript? I've searched around for a solution which works with a shell script (which I think will probably be a lot faster), but haven't been able to get any of them working.
I'm working on OSX Mountain Lion 10.8.4
--
edit
I see that I've uploaded the wrong version of the script I've managed to put together so far. Above is the script that is working, but it's really slow. Probably because it doesn't use any shell script.
---------------update-------------------
Here is the final script that is working pretty fast right now:
set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?"
set mgDestFolder to choose folder with prompt "Where is the destination folder?"
tell application "System Events"
set fileList to files of mgFilesFolder whose name does not start with "."
repeat with aFile in fileList
set prefix to my getPrefix(name of aFile)
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to POSIX path of destinationFolder
end try
end repeat
end tell
on getPrefix(aName)
try
set prefix to text 1 thru 7 of aName
return prefix
on error
return aName
end try
end getPrefix
The Finder is generally a slow program because it does a lot of things on your computer. Therefore you should avoid using it if possible. In your case these tasks can be done using System Events. Try this, maybe it will be faster. Note that you had a couple mistakes in your code which are fixed in this code.
set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?"
set mgDestFolder to choose folder with prompt "Where is the destination folder?"
tell application "System Events"
set fileList to files of mgFilesFolder whose name does not start with "."
repeat with aFile in fileList
set prefix to my getPrefix(name of aFile)
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to POSIX path of destinationFolder
end try
end repeat
end tell
on getPrefix(aName)
try
set prefix to text 1 thru 7 of aName
return prefix
on error
return aName
end try
end getPrefix
Not sure how many files you're working with, but I tested this with 10 folders and ~100 files, and it took less than 4 seconds to run. Working with strings is much faster than working with files, so the script gets the files/folders as strings and builds aliases when they're needed.
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
--Always use System Events whenever possible. It's WAY faster than Finder.
tell application "System Events"
set folderList to name of folders of mgDestFolder
set fileList to name of files of mgFilesFolder
end tell
repeat with i from 1 to (count folderList)
set folderName to item i of folderList
set filesToMove to {}
repeat with j from 1 to (count fileList)
set filename to item j of fileList
if filename begins with folderName then
set end of filesToMove to alias ((mgFilesFolder as string) & filename)
end if
end repeat
--Can't use system events for moving files. You have to use Finder.
tell application "Finder"
move filesToMove to alias ((mgDestFolder as string) & folderName & ":")
end tell
end repeat
It might be easier to use shell scripting:
cd FOLDER1; for f in *; do d=../FOLDER2/"${f:0:7}"*; [[ -d $d ]] && mv "$f" "$d"; done

Automator/Applescript File Sorting and Moving

I was wondering if there was a way in Automator to use Applescript code to get the extension of a file, and if it equals a specific extension (e.g. .pdf or .rtf) move to a specific folder for that extension (e.g if (extension == pdf) { move to folder "~/PDF Files" } else if (extension == rtf) { move to folder "~/Rich Text Files" })
Here's an applescript. Since your request was simple I just wrote it for you. Note how I get the file extension with the subroutine "getNameAndExtension(F)". Normally you can get the file extension from the Finder (called name extension) but I've found that the Finder is not always reliable so I always use that subroutine. That subroutine has always been reliable.
set homeFolder to path to home folder as text
set rtfFolderName to "Rich Text Files"
set pdfFolderName to "PDF Files"
-- choose the files
set theFiles to choose file with prompt "Choose RTF or PDF files to move into your home folder" with multiple selections allowed
-- make sure the folders exist
tell application "Finder"
if not (exists folder (homeFolder & rtfFolderName)) then
make new folder at folder homeFolder with properties {name:rtfFolderName}
end if
if not (exists folder (homeFolder & pdfFolderName)) then
make new folder at folder homeFolder with properties {name:pdfFolderName}
end if
end tell
-- move the files
repeat with aFile in theFiles
set fileExtension to item 2 of getNameAndExtension(aFile)
if fileExtension is "rtf" then
tell application "Finder"
move aFile to folder (homeFolder & rtfFolderName)
end tell
else if fileExtension is "pdf" then
tell application "Finder"
move aFile to folder (homeFolder & pdfFolderName)
end tell
end if
end repeat
(*=============== SUBROUTINES ===============*)
on getNameAndExtension(F)
set F to F as Unicode text
set {name:Nm, name extension:Ex} to info for file F without size
if Ex is missing value then set Ex to ""
if Ex is not "" then
set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
end if
return {Nm, Ex}
end getNameAndExtension
I'm not at my Apple right now, so I can't play around with Automator and figure it out. But if you could do this by switching finder to list view, sort by type, and then select blocks of files of the same type and drag them into the right folder.

Resources