1994firehawk

Q: Applescript to move files that are > 30 days old

Hi, I'm looking for a folder action script to move files that are more than 30 days old from my "NEW" file folder at:  volumes/files/NEW  to my "OLD"  file folder:  volumes/files/OLD  folder.  I've searched and have only found scripts to delete old files using the "date modified" info for the files. Any help is appreciated.

Mac mini, OS X Mavericks (10.9.5)

Posted on Aug 3, 2016 12:41 PM

Close

Q: Applescript to move files that are > 30 days old

  • All replies
  • Helpful answers

  • by Niel,

    Niel Niel Aug 3, 2016 1:17 PM in response to 1994firehawk
    Level 10 (311,758 points)
    Aug 3, 2016 1:17 PM in response to 1994firehawk

    Use code such as:

     

    tell application "Finder"

    move every file of folder "Files:New" whose modification date is less than (current date) - (30 * days) to folder "Files:Old"

    end tell

     

    (143820)

  • by 1994firehawk,

    1994firehawk 1994firehawk Aug 4, 2016 11:17 AM in response to Niel
    Level 1 (4 points)
    Mac OS X
    Aug 4, 2016 11:17 AM in response to Niel

    Thanks for the response. When I tried to use the code I found that it doesn't do what I want to do. By using the "modified date" the files are moved right away because they are already older than 30 days.

     

    What I want to do is to move video files 30 days after they are copied into my "new" folder.

     

    The "modified date" doesn't change by copying the file. Also I don't want to have to open the file before or after copying to use the "last opened" date.  Is this possible?

    Thanks.

  • by Niel,

    Niel Niel Aug 7, 2016 2:45 PM in response to 1994firehawk
    Level 10 (311,758 points)
    Aug 7, 2016 2:45 PM in response to 1994firehawk

    As far as I know, no.

     

    (143893)

  • by Jacques Rioux,

    Jacques Rioux Jacques Rioux Aug 8, 2016 9:46 AM in response to 1994firehawk
    Level 4 (3,408 points)
    Mac OS X
    Aug 8, 2016 9:46 AM in response to 1994firehawk

    Hi,

     

    It's possible to get the value of the "Date Added" metadata of the file.


    First solution:

    Works on Yosemite or El Capitan only.

    The script use the methods of the NSFileManager class and the NSURL class to get the value of the NSURLAddedToDirectoryDateKey key of the file

    Caveat: This key is not supported on some format of the volume

     

    The AppleScript :

    -- this script move files (> 30 days old)
    set sourceFolder to "/files/NEW/" as POSIX file as alias
    set destFolder to "/files/OLD/" as POSIX file as alias
    
    set pyScript to quoted form of "import sys, os; from Foundation import NSFileManager, NSURL, NSDate, NSDirectoryEnumerationSkipsHiddenFiles
    d_URL = NSURL.fileURLWithPath_isDirectory_(sys.argv[2].decode(\"utf8\"), True)
    f_URL = NSURL.fileURLWithPath_isDirectory_(sys.argv[1].decode(\"utf8\"), True)
    dfM = NSFileManager.defaultManager()
    thirtydaysAgo = NSDate.dateWithTimeIntervalSinceNow_(-86400 * 30)
    myKeys = ['NSURLIsDirectoryKey', 'NSURLAddedToDirectoryDateKey']
    p = dfM.contentsOfDirectoryAtURL_includingPropertiesForKeys_options_error_(f_URL, myKeys, NSDirectoryEnumerationSkipsHiddenFiles, None)[0]
    for f in p:
        myDict, error = f.resourceValuesForKeys_error_(myKeys, None)
        if error is None and not (myDict['NSURLIsDirectoryKey']): 
            if (myDict['NSURLAddedToDirectoryDateKey'].compare_(thirtydaysAgo) == -1):
                destFile = d_URL.URLByAppendingPathComponent_(f.lastPathComponent())
                b, e = dfM.moveItemAtURL_toURL_error_(f, destFile , None)
                if (not b): print f.path().encode('utf8')"
    
    set r to do shell script "/usr/bin/python -c " & pyScript & " " & (quoted form of POSIX path of sourceFolder) & " " & quoted form of POSIX path of destFolder
    
    if r is not "" then -- Some files have not been moved, because of some error (name already exists in the destination folder, permissions issue, ...)
        set FileList to paragraphs of r -- get list of paths (each path is the type posix)
        -- do something with this list (if you need it)
    end if
    

     

     

    Second solution:

    The script use the mdls command to get the kMDItemDateAdded value of the file.

    Caveat: doesn't work when the volume or the folder is not indexed by Spotlight

     

    The AppleScript:

    -- this script move files (> 30 days old)
    set sourceFolder to "/files/NEW/" as POSIX file as alias
    set destFolder to "/files/OLD/" as POSIX file as alias
    set thirtydaysAgo to (current date) - (0 * days)
    
    tell application "Finder"
        repeat with f in (get files of sourceFolder)
            set thisDate to my getDateAdded(f as string)
            if thisDate is not "(null)" and thisDate < thirtydaysAgo then
                try
                    move f to destFolder
                on error
                    --- do something on error
                end try
            end if
        end repeat
    end tell
    
    on getDateAdded(f)
        set t to do shell script "mdls -name kMDItemDateAdded -raw " & quoted form of POSIX path of f
        if t is "(null)" then return t
        tell t to set {y, mo, d, h, mi, s} to {text 1 thru 4, text 6 thru 7, text 9 thru 10, text 12 thru 13, text 15 thru 16, text 18 thru 19}
        set tgmt to (time to GMT)
        tell (current date)
            set {its year, its month, its day, its hours, its minutes, its seconds} to {y, mo, d, h, mi, s}
            return it + tgmt
        end tell
    end getDateAdded
    
  • by 1994firehawk,Solvedanswer

    1994firehawk 1994firehawk Aug 10, 2016 7:40 AM in response to Jacques Rioux
    Level 1 (4 points)
    Mac OS X
    Aug 10, 2016 7:40 AM in response to Jacques Rioux

    Hi again, thanks for your help Jacques in crafting an applescript. I was not able to open your 2 scripts in my editor without getting an error, however I also had help from Yvan Koenig and Shane Stanley of    www.Macscripter.net  

    and was testing their script when you sent your versions.

     

    They crafted the following script that worked just as I needed it to.

     

    Also, if someone else needs a script to move a file after a certain number of days you can modify the last 3 lines of this code. Instead of "volumes/files/NEW" , input your folder paths; and instead of 30 on the last line, put in any number of days you want, 10, 18, 27 etc. I am using this as an Automator Application to be run as a startup item.

     

     

    Thanks again for all the help. This one is SOLVED.

     

     

    The script:

     

    use AppleScript version "2.4" -- Yosemite (10.10) or later

    use framework "Foundation"

    use scripting additions

     

    on moveFilesFrom:posixFolderPath toFolder:destPosixPath numberOfDaysOld:numDays

      -- get date limit

      set dateLimit to current application's NSDate's dateWithTimeIntervalSinceNow:-(numDays * days)

      set dateLimit to current application's NSCalendar's currentCalendar()'s startOfDayForDate:dateLimit

      -- make URLs of POSIX paths

      set destFolderURL to current application's |NSURL|'s fileURLWithPath:destPosixPath

      set sourceFolderURL to current application's |NSURL|'s fileURLWithPath:posixFolderPath

      -- get file manager

      set theNSFileManager to current application's NSFileManager's defaultManager()

      -- get contents of directory, ignoring invisible items

      set theURLs to theNSFileManager's contentsOfDirectoryAtURL:sourceFolderURL includingPropertiesForKeys:{} options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)

      -- loop through URLs

      repeat with aURL in theURLs

      -- get date added

      set {theResult, theDate} to (aURL's getResourceValue:(reference) forKey:(current application's NSURLAddedToDirectoryDateKey) |error|:(missing value))

      -- test date

      if theResult as boolean and (theDate's compare:dateLimit) as integer < 0 then

      -- get name of file

      set theName to aURL's lastPathComponent()

      -- make new URL

      set destURL to (destFolderURL's URLByAppendingPathComponent:theName)

      -- move file

      (theNSFileManager's moveItemAtURL:aURL toURL:destURL |error|:(missing value))

      end if

      end repeat

    end moveFilesFrom:toFolder:numberOfDaysOld:

     

    #=====

     

    # Define your own paths here

     

    set posixFolderPath to "volumes/files/NEW"

    set destPosixPath to "volumes/files/OLD"

     

    my moveFilesFrom:posixFolderPath toFolder:destPosixPath numberOfDaysOld:30