EDIT 2019/07/15 20:39 CDT:
● Added a working macro in addition to the bare AppleScript.
Hey Folks,
This comes up over and over, so I'm posting it independently.
The only way to reliably detect the last-added file in a folder (directory) is to use AppleScriptObjC.
(Unless you iterate through a file list and test the added-date attribute in a Keyboard Maestro action.)
This script will get the last file path.
OR – if you change the returningSingleItem
flag to false it will return a list of files paths sorted by last-added.
Currently it ignores folders, but that can be changed in the code.
Get the Last File Added to a Directory (Folder) v1.00.kmmacros (12 KB)
AppleScript Code
------------------------------------------------------------------------------
# Auth: Christopher Stone { Heavy Lifting by Shane Stanley }
# dCre: 2015/09/15 20:08
# dMod: 2017/01/09 21:48
# Appl: ASObjC
# Task: Get the last-added file from a folder (directory) OR
# : Get a list of Files sorted by Last-Added (other sort-keys listed for convenience).
# Libs: None
# Osax: None
# Tags: @Applescript, @ASObjC, @Script, @Sorted, @File, @List, @Shane, @Last, @Added, @ccs, @ccstone
# Note: Tested only on macOS 10.10.5, 10.11+, 10.12.2
------------------------------------------------------------------------------
use framework "Foundation"
use scripting additions
------------------------------------------------------------------------------
set targetFolder to path to downloads folder -- User to change as needed.
set thePath to POSIX path of targetFolder
set theSortKey to (current application's NSURLAddedToDirectoryDateKey)
set theItem to its filesIn:thePath sortedBy:theSortKey returningSingleItem:true
------------------------------------------------------------------------------
--» HANDLERS
------------------------------------------------------------------------------
on filesIn:folderPOSIXPath sortedBy:sortKey returningSingleItem:singleItemBoolVal
# Specify keys for the values we want for each item in the folder.
# We want the path, whether it's a directory, whether it's a package, and the key to sort on.
set keysToRequest to {current application's NSURLPathKey, ¬
current application's NSURLIsPackageKey, ¬
current application's NSURLIsDirectoryKey, ¬
sortKey}
# Make a NSURL for the folder because that's what's needed.
set theFolderURL to current application's class "NSURL"'s fileURLWithPath:folderPOSIXPath
# Get a reference to the file manager.
set theNSFileManager to current application's NSFileManager's defaultManager()
# Get the NSURLs of items in folder while at the same time getting values for our keys and skipping invisible items.
set listOfNSURLs to (theNSFileManager's contentsOfDirectoryAtURL:theFolderURL ¬
includingPropertiesForKeys:keysToRequest ¬
options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) ¬
|error|:(missing value))
# Create an array in which to store just the key values.
set valuesNSArray to current application's NSMutableArray's array()
# Loop through the NSURL list retrieving key values and adding each set as a dictionary/record to the array/list.
repeat with oneNSURL in listOfNSURLs
(valuesNSArray's addObject:(oneNSURL's resourceValuesForKeys:keysToRequest |error|:(missing value)))
end repeat
# Filter out all non-packages directories using a predicate.
set theNSPredicate to current application's NSPredicate's predicateWithFormat_("%K == NO OR %K == YES", current application's NSURLIsDirectoryKey, current application's NSURLIsPackageKey)
set valuesNSArray to valuesNSArray's filteredArrayUsingPredicate:theNSPredicate
# Make a sort descriptor that describes the specific sort key.
set theDescriptor to current application's NSSortDescriptor's sortDescriptorWithKey:(sortKey) ascending:true
# Sort the array.
set theSortedNSArray to valuesNSArray's sortedArrayUsingDescriptors:{theDescriptor}
if singleItemBoolVal = false then
# Extract just the paths and convert to an AppleScript list.
return (theSortedNSArray's valueForKey:(current application's NSURLPathKey)) as list
else
# If you want the single most-recent file, use this instead of the previous line.
return (theSortedNSArray's lastObject()'s valueForKey:(current application's NSURLPathKey)) as text
end if
end filesIn:sortedBy:returningSingleItem:
------------------------------------------------------------------------------
(*
OTHER SORT CRITERIA
NSURL AddedToDirectoryDateKey
NSURL AttributeModificationDateKey
NSURL ContentAccessDateKey
NSURL ContentModificationDateKey
NSURL CreationDateKey
NSURL FileAllocatedSizeKey
NSURL FileSizeKey
NSURL LabelColorKey
NSURL LabelNumberKey
NSURL LocalizedLabelKey
NSURL LocalizedTypeDescriptionKey
NSURL NameKey
NSURL TotalFileAllocatedSizeKey
NSURL TotalFileSizeKey
NSURL TypeIdentifierKey
* REMOVE THE SPACE AFTER 'NSURL' TO USE!
*)
------------------------------------------------------------------------------
-Chris