Want to highlight a helpful answer? Upvote!

Did someone help you, or did an answer or User Tip resolve your issue? Upvote by selecting the upvote arrow. Your feedback helps others! Learn more about when to upvote >

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

how to get latest added file from a folder using apple script

Hi..

I am trying to get a latest added file from a folder..and for this i have below script


tell application "Finder"

set latestFile to item 1 of (sort (get files of (path to downloads folder)) by creation date) as alias

set fileName to latestFile's name

end tell


By using this i am not able to get latest file because for some files the creation date is some older date so is there any way to get latest file based on "Date Added" column of a folder.

Posted on Nov 14, 2012 8:55 PM

Reply
Question marked as Best reply

Posted on Nov 14, 2012 10:42 PM

You can't do this in the way you're tryng, because the sort command can sort data based on any property, but the date a file was added to a folder is not part of the file's data - it's part of the metadata associated with the folder itself, and the Finder doesn't expose that data to AppleScript.


What is it you're trying to achieve? At face value, without knowing more data, you might be able to solve the problem via Folder Actions, which are AppleScripts that fire when a folder is modified in some way (e.g. opened, closed, added to or deleted from). You may be able to write a Folder Action that affects new files as they are added to the folder, or at the very least create a manual record of the last file added that you can later affect.

10 replies
Question marked as Best reply

Nov 14, 2012 10:42 PM in response to rajaharish

You can't do this in the way you're tryng, because the sort command can sort data based on any property, but the date a file was added to a folder is not part of the file's data - it's part of the metadata associated with the folder itself, and the Finder doesn't expose that data to AppleScript.


What is it you're trying to achieve? At face value, without knowing more data, you might be able to solve the problem via Folder Actions, which are AppleScripts that fire when a folder is modified in some way (e.g. opened, closed, added to or deleted from). You may be able to write a Folder Action that affects new files as they are added to the folder, or at the very least create a manual record of the last file added that you can later affect.

Nov 15, 2012 5:43 AM in response to rajaharish

The 'ls' command only has options to sort files vis modification date, last accessed time, and the last time the file's metadate was modified (frequently the same as modification time, but not always, such as when the file's permissions are changed, but the file data is unchanged).


I think Camelot's suggest to use a Folder Action is your best bet. For example, create a folder action that changes the modification (mtime) or metadata change time (ctime) when a new files is added to the directory (I'm assuming a folder action can be told which files are being touched when the folder action triggers).


Or have your script maintain a list of previously seen files, and then check the current files against the list, and any file not in the list must be new (or it was renamed). After getting your new file(s), update your list. Of course if you have multiple added new files you would be handed more than 1 file to handle.

Nov 15, 2012 10:56 AM in response to rajaharish

Not via ls, no. If you're opposed to a Folder Action the closest you can get is using mdls to extract the 'Date Added' metadata and (manually) sort on that. For example:

$ mdls -name kMDItemFSName -name kMDItemDateAdded ~/*

This command will list the name and date added of every file in your home directory. You'd need to parse that data and sort it to find the most recent item. Not trivial, but all I can think of off-hand. To me, that Folder Action is looking more and more appealing by the minute 😉

Nov 19, 2012 9:06 AM in response to rajaharish

If you don't mind using GUI Scripting (you must enable access for assistive devices in the Accessibility System Preference pane), the following script should give you a reference to the last item added to any folder. Admittedly not the most elegant solution, but it works, at least under OS X 10.8.2.




set theFolder to choose folder


tell application "Finder"

activate

set theFolderWindow to container window of theFolder

set alreadyOpen to existstheFolderWindow

tell theFolderWindow

open

set theInitialView to current view

set current view to icon view

end tell

end tell


tell application "System Events" to tell process "Finder"

-- Arrange by None:

set theInitialArrangement to name of menu item 1 of menu 1 of menu item "Arrange By" of menu 1 of menu bar item "View" of menu bar 1 whose value of attribute "AXMenuItemMarkChar" is ""

keystroke "0" using {control down, command down}


-- Sort by Date Added:

set theInitialSortingOrder to name of menu item 1 of menu 1 of menu item "Sort By" of menu 1 of menu bar item "View" of menu bar 1 whose value of attribute "AXMenuItemMarkChar" is ""

keystroke "4" using {control down, option down, command down}


-- Get the name of the last item:

set theItemName to name of image 1 of UI element 1 of last scroll area of splitter group 1 of (window 1 whose subrole is "AXStandardWindow")


-- Restore the initial settings:

clickmenu itemtheInitialSortingOrder of menu 1 of menu item "Sort By" of menu 1 of menu bar item "View" of menu bar 1

clickmenu itemtheInitialArrangement of menu 1 of menu item "Arrange By" of menu 1 of menu bar item "View" of menu bar 1

end tell


tell application "Finder"

set current view of theFolderWindow to theInitialView-- restore the initial view

if not alreadyOpen then closetheFolderWindow

set theLastItem to itemtheItemName of theFolder

end tell


theLastItem



Message was edited by: Pierre L.

Nov 19, 2012 9:18 AM in response to rajaharish

Another option is to use a folder action or launchd item reset the creation or modification date to the current date whenever a file is added to the folder. e.g.:


on adding folder items tothis_folderafter receivingthese_items

tell application "System Events"

repeat with this_item in these_items

set modification date of this_item to (current date)

end repeat

end tell

end adding folder items to


That way sorting by modification date is the same as sorting by file addition date. You'll have to work out how to handle when multiple files are added at the same time, of course.

Dec 1, 2013 12:06 AM in response to rajaharish

Just chiming in on this, in case anyone is still paying attention. Oddly 10.9 Mavericks seems to give the oldest file, not the newest file. Did something like


tell application "Finder"

set latestFile to item 1 of (sort (get files of (path to downloads folder)) by creation date) as alias

set fileName to latestFile'sname

end tell


return the newest file before? Because it's showing the oldest now.

Jul 16, 2014 3:33 AM in response to rajaharish

I do it like this:

Return List of Aliases for Items based on Time Added to Folder.scpt


set dirSel to path tohome folder

set filteredList to my listFilesTimeOfCreation(dirSel, 1000) -- positive Input


repeat with theItem in filteredList

get theItem as string

end repeat


on listFilesTimeOfCreation(dirInputAlias, timeAgoPositiveIntegerInMinutes)


-- Returns list

set timeInterval to timeAgoPositiveIntegerInMinutes * 60 * 60 - 1 -- convert to negative number (time past, not time into future) and convert to minutes-- ## -5 * 60 -- 1 measured in milliseconds e.g. -1*60 = 1 minute ago


-- 5 minutes ago = -5 * 60

set filteredList to {}



-- Check downloads folder and list files older than N minutes.

set locateDateAdded to "mdfind -onlyin " & quoted form of POSIX path of dirInputAlias & " 'kMDItemDateAdded>$time.now(" & timeInterval & ")&&kMDItemFSName=\"*.*\"c'"

set filteredItemsOutput to do shell scriptlocateDateAdded


tell application "Finder"

repeat with itemStep from 1 to count of paragraphs of filteredItemsOutput

set thisItem to paragraphitemStep of filteredItemsOutput

set end of filteredList to POSIX file thisItem as alias

end repeat

end tell

return filteredList-- list of aliases

end listFilesTimeOfCreation


Jul 24, 2014 7:47 PM in response to rajaharish

Hi Rajaharish,


I know this is a bit late, but I ran into this problem, tried the code below and it worked. For Mavericks, I just changed it to the "Last item" instead of item 1.


---------------

tell application "Finder"

set latestFile to the last item of (sort (get files of (path to downloads folder)) by creation date) as alias

set fileName to latestFile's name

display dialog "the file's name is: " & fileName

end tell


--------------------


tell

how to get latest added file from a folder using apple script

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.