Applescript to find the newest folder - applescript

I'm trying to find the folder which has been last modified. (Actually, I'm only interested in that folder and not an ordered list.) I'm getting an -10010 error.
tell application "Finder"
try
set latestFolder to item 1 of (sort (get name of folders of folder ("/Users/c64/Desktop" as POSIX file)) by creation date) as alias
set folderName to latestFolder's name
end try
end tell

If you're looking for the name of the last modified folder on the Desktop, then this will do it:
tell application "Finder"
set latestModifiedFolderName to name of item 1 of (sort every folder by modification date)
end tell
By the way, the AppleScript Dictionary for Finder does not contain terms POSIX file or POSIX path and when using e.g. POSIX file inside of a tell application "Finder" block, Finder will throw a non-fatal error if it can be coerced into an alias, otherwise it can throw a fatal error. That said, if you are dealing with a POSIX path, it's probably best to pass it to Finder as an alias, and I'd recommend coercing the POSIX path to an alias before passing it to Finder, e.g.:
set thisFolderPath to POSIX file "/Path/To/Some/Folder" as alias
tell application "Finder"
set latestModifiedFolderName to name of item 1 of (sort every folder of thisFolderPath by modification date)
end tell
Note: The example AppleScript code above is just that, and does not include any error handling as may be appropriate/needed/wanted, the onus is upon the user to add any error handling for any example code presented and or code written by the oneself.

Related

AppleScript code works on High Sierra, but not on Monterey

I want to look into a folder to select every file whose name contains "abc".
Here is my AppleScript code:
set myFolder to (((path to library folder from user domain) as string) & "FOLDER") as alias
tell application "Finder"
set deleted123 to every file of folder myFolder whose name contains "abc"
repeat with oneFile in deleted123
if exists (deleted123) then set end of deleted123 to oneFile & return
--Do something
end repeat
if deleted123 ≠ {} then
--Do something else with the selected.
end if
end tell
The code works flawlessly on High Sierra, i.e., it finds out all the files whose names contain "abc", but it doesn't on Monterey.
What is the problem? How can this piece of code be improved?
Help highly appreciated.
There are two major mistakes:
myFolder is an alias specifier. You add the folder keyword which is a double reference, delete as alias in the first line
oneFile is a Finder file specifier, you cannot append the string return. Maybe the file specifier is silently coerced to string in Sierra. If you want to use the file references then the return statement makes no sense anyway.
Another bad practice is to modify the array deleted123 while being enumerated. Create an extra variable.
And the repeat loop makes no sense either because exists (deleted123) is always true and even if you check the current item in the loop oneFile it's always true.

AppleScript - exclude certain files when duplicating a folder from one location to another

I have an AppleScript that is working to duplicate the contents of a source folder to a destination folder. I now need to add some conditional logic to this so that it excludes certain files from the source folder and doesn't copy across all files/folders.
Here's my current script:
set here to POSIX file "/Users/benny/Desktop/Projects/Source/Project1"
set there to POSIX file "/Users/benny/Documents/Masters"
tell application id "com.apple.Finder" to duplicate ¬
every item in the folder here to there
I would like to add some logic so that it doesn't copy across these files:
Import.log
Recover.log
Haven't tried to get the syntax working here but haven't been able to work out how to exclude files by their filename so far.
The duplicate command is wrapped in a try statement because it will error out if items of the same name already exist in there. You could uncomment the with replacing and get rid of the try statement, that is if replacing an existing item is okay.
set here to POSIX file "/Users/benny/Desktop/Projects/Source/Project1"
set there to POSIX file "/Users/benny/Documents/Masters"
tell application id "com.apple.Finder"
set theseItems to a reference to ¬
(items whose name is not equal to "Import.log" and ¬
name is not equal to "Recover.log") of folder here
try
duplicate theseItems to there -- with replacing
end try
end tell

How to fix a ~10006 error in applescript when duplicating a file to another folder?

When trying to duplicate files to another folder, the script throws a ~10006 error. This only occurs on some Mac mini computers and works fine on others. I have no idea why it is working on some computers but not on others.
This is the error shown:
Can't set "Macintosh HD:Users:username:Documents:" to <> "Macintosh HD:Users:username:Downloads:new test:portal resources" of application "Finder". (~10006)
tell application "Finder"
set folderToBeMoved to (container of (path to me) as text) &
"portal_resources"
set destinationFolder to path to documents folder as text
set moveFolder to duplicate folder folderToBeMoved to destinationFolder with replacing
end tell
expected output is duplicating file to documents folder. But, when testing on certain Macs, the script shows an error ~10006. It works on other macs perfectly well.
You are going to copy the folder to a literal string (path) which can fail on machines running older system versions.
Remove the as text parameter to get an alias specifier
set destinationFolder to path to documents folder
Try this code:
tell application "Finder"
set folderToBeMoved to folder "portal_resources" of container of (path to me)
set destinationFolder to path to documents folder
set moveFolder to duplicate folderToBeMoved to destinationFolder with replacing
end tell
There were two issues here that I've changed. First, you convert things to text strings and try to modify the strings, but the Finder has a rich language for talking about file objects. You should just leave everything in object form. For instance, this:
folder "portal_resources" of container of (path to me)
tells the finder to find the folder of that name in that container and return an object specifier that you can use directly.
Second, once you have this object, you can't add the 'folder' specifier to it. Where you say:
duplicate folder folderToBeMoved
folderToBeMoved is already an object specifier (an object of the form 'folder [path]') so you're actually asking the Finder for 'folder folder [path],' which throws the error you're seeing. It's like saying to someone "pass the 'pass the salt.'" People are probably smart enough to figure that out; the Finder isn't.

Applescript / Finder select specific items in a folder including those in disclosed subfolders by file name or file path list

Here's our situation:
We have a list of file names and/or full file paths (we can generate either)
The files in our list are all contained under one folder, but scattered across multiple sub-folders. (There are hundreds of items in our select list from thousands of possible files. Selecting manually isn't an option)
We've got the root folder open in list view and all sub-folders, sub-sub etc disclosure-opened (btw thanks to http://hints.macworld.com/article.php?story=20030218164922494 for the shortcut "command, option, control and shift when pressing the right arrow")
With all files visible under one window open we want to automatically select all the items in our file list so that they can then be dragged at once to an application.
I do not believe that with basic AppleScript one can programmatically select multiple items in Finder which span throughout different folders and subfolders within a given folder in one window. Maybe with Cocoa-AppleScript, don't know, however if Avid can open files from file aliases, then the following example AppleScript code is a viable option.
The example AppleScript code makes the following assumptions:
There is a plain text file containing the fully qualified POSIX pathnames of the target files to be processed with Avid and the name of the file is: List of Files to Process with Avid.txt
The name of the folder containing the aliases is: Aliases of Files to Process with Avid
The Desktop is used as the location in the filesystem that the aforementioned file and folder exists, to be processed by Avid.
Obviously these settings can be changed as needed/wanted, see the comments in the code.
Example AppleScript code:
-- # Set the value of the following three property variables:
-- #
-- # The value of 'thisLocation' is an colon-delimited path string, e.g. 'path to desktop as string' returns: "Macintosh HD:Users:me:Desktop:"
-- # NOTE: When not using 'path to (folder)' where 'folder' is a 'folder constant' , the special folder for which to return the path, the value should be in the form of an colon-delimited path string.
-- # See: https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW19
-- #
-- # The value of 'theListFilename' is the name of the plain text file containing the fully quilified pathnames of the target files to be opened in Avid.
-- # The value of 'theFolderName' is the name of the temporary folder the temporary aliases will be created in. This folder gets created new each run with new aliases.
-- #
-- # NOTE: For ease of use, as each run is presumed to be temporary to get that job run done, the location of the 'theListFilename' and 'theFolderName' are both in 'thisLocation'.
property thisLocation : (path to desktop as string)
property theListFilename : "List of Files to Process with Avid.txt"
property theFolderName : "Aliases of Files to Process with Avid"
-- # The remaining code is tokenized and should not need to be modified.
tell application "Finder"
if (exists thisLocation & theListFilename) then
tell current application to set theList to read alias (thisLocation & theListFilename)
else
display dialog "The file, \"" & theListFilename & "\", was not found at the expected location." buttons {"OK"} ¬
default button 1 with title "Missing File" with icon 0
return
end if
set theFolderPathname to thisLocation & theFolderName
if not (exists theFolderPathname) then
make new folder at thisLocation with properties {name:theFolderName}
else
move theFolderPathname to trash
make new folder at thisLocation with properties {name:theFolderName}
end if
repeat with i from 1 to length of theList
try
make new alias file at theFolderPathname to POSIX file (paragraph i of theList)
end try
end repeat
reveal theFolderPathname
activate
-- delay 1 -- # In necessary, uncomment and adjust value as appropriate.
select every item of alias theFolderPathname
end tell
In Script Editor, save this script and an application, e.g. Select Files to Process with Avid, and then run as needed after replacing the e.g. List of Files to Process with Avid.txt with the current set of target files to be processed with Avid.
The script does the following:
Checks to see the file e.g. List of Files to Process with Avid.txt exists and if not displays error message and exits.
Checks to see if the folder e.g. Aliases of Files to Process with Avid exist and if not creates it, and if it exists, moves it to the Trash and creates it anew, for the new run of target files to be processed.
Creates an alias of each file listed, as a fully qualified POSIX pathname, in the file e.g.: List of Files to Process with Avid.txt
Opens the folder, e.g. Select Files to Process with Avid, in Finder and selects the aliases.
You are now ready to drag and drop the selected aliases to Avid.
Note: This script assumes the fully qualified POSIX pathnames of the target files to be processes with Avid do not contain linefeeds, carriage returns and or null characters in their pathnames.
This works using the latest version of Sierra.
I was not able to figure out a way to selectively select files in folders with subfolders with subfolders etc. The only solution I was able to come up with was to create folder called “Aliases” and have AppleScript create alias files to all of the ”selected files” and store all of the aliases in the aliases folder. From there you can drag all of the files and drop them into your application as you desired
If you have a plain text file containing POSIX path filenames, each on a separate line like the example in this next image, this version will load the pathnames from the text file directly into the script. Just save this script as an application. You can drag text files directly onto the icon of the app because the code is set up to be a droplet
global theFile
property theInfo : missing value
property theName : missing value
property theList : {}
property theList2 : {}
property aliasFolder : (path to desktop as text) & "Aliases"
on open theFiles
set theInfo to info for theFiles
set theName to POSIX path of theFiles
getLinesofFileAsList(theName)
tell application "Finder"
if not (exists of alias aliasFolder) then
make new folder at (path to desktop as text) with properties {name:"Aliases"}
end if
delete every item of alias aliasFolder
end tell
repeat with i from 1 to count of theList
try
set theResult to POSIX file (item i of theList) as text
set end of theList2 to theResult
tell application "Finder"
set theAliases to make new alias file at aliasFolder to theResult
end tell
end try
end repeat
delay 0.5
tell application "Finder"
activate
delay 0.5
set hmmm to reveal aliasFolder
delay 0.5
set hmmm to select every item of alias aliasFolder
activate hmmm
end tell
end open
on getLinesofFileAsList(theName)
set theFile to theName
set theFile to POSIX path of theName
set theList to read POSIX file theFile as text
set saveTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set theList to paragraphs of theList
if last item of theList is "" then
set theList to reverse of rest of reverse of theList
end if
set AppleScript's text item delimiters to saveTID
end getLinesofFileAsList
--on run
-- -- Handle the case where the script is launched without any dropped files
--end run

list subfolders using applescript

This is my first applescript. I thought I'd do something simple like navigating to a folder using a path and listing the subfolders...Unfortunately, I can't figure it out :-)
Here is what I've tried so far:
The first try:
tell application "Finder"
set the_folder to POSIX path of "Users:MyName:Doc"
log the_folder
set folder_list to every item of folder the_folder
log folder_list
end tell
This produces an error:
"Finder got an error: Can't get folder "/Users/MyName/Doc".
Could someone please:
1. Explain to me what I'm doing wrong.
2. Provide an example that works.
Thanks in advance.
btw the folder does exist on my machine...
UPDATE: Oops! It appears that I have given you the wrong information so I will give you the correct information.
The command POSIX path of requires a complete alias reference. By that I mean supplying the full file reference (i.e. <your_disk_name>:Users:<your_user_name>:somefolder:). Make sure that if you're referring to a folder that you end the reference with a colon (i.e. Macintosh HD:Users:). An improved version would look like this:
tell application "Finder"
set the_folder to (POSIX path of ("<your_disk_name>:Users:<your_user_name>:Doc:") as alias) as alias
set folder_list to every item of the_folder
end tell
OPTIONAL
To coerce a POSIX path (i.e. /Users/<your_user_name>/somefolder) back into an alias, two conversions are needed.
Conversion 1: The first step is to convert the reference into a file reference. To do this, place the words as POSIX file after the reference, like so:
"/Users/<your_user_name>/somefolder" as POSIX file
This code procudes a file reference in this form: file "<your_disk_name>:Users:<your_user_name>:somefolder:"
Conversion 2: Add a second coercion, as alias, to the end of the reference...
"/Users/<your_user_name>/somefolder" as POSIX file as alias
This code produces an actual alias reference: alias "<your_disk_name>:Users:<your_user_name>:somefolder:
If you have any questions, just ask. :)
Posix paths are paths you use at the command line and are "/" delimited. Applescript paths are ":" separated so just use those. Try this script to see what the path should look like...
set folderPath to (choose folder) as text

Resources