I have this AppleScript code, which gets the latest file from my downloads folder.
It needs to be adjusted to your path.
tell application "Finder"
set latestFile to the last item of (sort (get files of (path to downloads folder)) by creation date) as alias
set p to POSIX path of latestFile
end tell
set dbPath to (path to home folder as text) & "Dropbox:"
set tmFldr to dbPath & "CT:TM:"
tell application "Finder"
set latestFolder to the last item of (sort (get folders of (path to tmFldr)) by modification date) as alias
set folderName to latestFolder's name
display dialog "the folder's name is: " & folderName
end tell
With your (path to tmFldr) I get an error. However, it works with get folders of folder tmFldr
AFAIK a folder’s modification date does not change when the modification date of a file in that folder changes. (It changes only when you add or remove a file from the folder.)
You can use Keyboard Maestro to scan a folder (or folders) using the For Each action and the Folder Contents collection. Add a collection for each folder if appropriate, or scan the parent folder.
You can use the Get File Attribute action to get the type of the file (to restrict it to File types), and also to get the modification or added date. Scan through and fine the latest date and save the date and the path.
At the end you’ll have the path of the latest (added or modified) file.
This has one major pitfall. If you have .app files or any sort of bundle file (e.g. a directory the Finder shows as a file), the shell script will descend into it.
It runs in about 1/2 second on a directory with many subfolders and about 13,000 files and will be much faster on a smaller directory tree.
There's a way to stop find from descending into bundles, but it's a little complicated – and I don't have it at my fingertips. I'll post that later if I can find it without too much trouble.
I'll also post an AppleScriptObjC script later that will ignore bundles.
It works fine for a relatively small directory, but it gets progressively slower as the number of files in the directory grows.
A folder with 500 files in it takes nearly 10 seconds to process on my system.
You can make your code recursive by using entire contents:
set targetFolder to alias ((path to documents folder as text) & "Code_Projects:Script_Debugger:Saved-Sessions:")
tell application "Finder"
set latestFile to the last item of (sort (get files of entire contents of targetFolder) by modification date) as alias
end tell
set latestFilePath to POSIX path of latestFile
But entire contents has always been grossly slow, and I wouldn’t recommend it.
Note that I’ve pulled the POSIX Path coercion out of the Finder-tell-block. Apple engineers recommend that all calls to osaxen (in this case StandardAdditions) be placed outside of application-tell-blocks.