Moving entire folders with AppleScript - applescript

This is my very first use of AppleScript. I'm trying to use it to move a 100+ folders (and their content files) from one location to another. I'm not just moving the files because I want to maintain the filing system. So I've got the folders listed in a .txt file in this format:
Macintosh HD:Users:Tom:Music:iTunes:Afrika Bambaataa
Macintosh HD:Users:Tom:Music:iTunes:Air
And then I run the following in AppleScript:
tell application "Finder"
set TextFile to (choose file with prompt "Select your text file" of type {"txt"})
set My_Folder to (choose folder with prompt "Select your destination folder")
set List_files to paragraphs of (read TextFile)
move List_files to My_Folder
end tell
However the error I receive is the following:
error "Finder got an error: Handler can’t handle objects of this class." number -10010
Any help on what I'm doing wrong here?
Much appreciated!

tell application "Finder"
set TextFile to (choose file with prompt "Select your text file" of type {"txt"})
set My_Folder to (choose folder with prompt "Select your destination folder")
set List_files to paragraphs of (read TextFile)
move List_files to My_Folder
end tell
Currently, List_files is just a list of text objects, i.e.
{"Macintosh HD:Users:Tom:Music:iTunes:Afrika Bambaataa",
"Macintosh HD:Users:Tom:Music:iTunes:Air", ...}
so what you're asking Finder to do is move some text to a folder, which doesn't make sense. You need to tell Finder that this text represents a path to a folder, by using the folder specifier. Since this can't be done en masse, you have to iterate through the list:
repeat with fp in List_files
move folder fp to My_Folder
end repeat
However, I wouldn't actually do it like this, as that will require 100+ separate move commands - one for each item in List_files. Instead, we'll edit the list items first by prepending the folder specifier to each item, and then move the list of folders altogether in a single command:
repeat with fp in List_files
set fp's contents to folder fp
end repeat
move List_files to My_Folder
Depending how big the files are and how long the transfer will take, the script might time out before the transfer is complete. I'm not honestly sure what impact this would have on an existing file transfer. I suspect that AppleScript will simply lose its connection with Finder, but that the transfer will continue anyway since the command has already been issued (another benefit of using a single move command instead of multiples). But, if you want to avoid finding out, we can extend the timeout duration to be safe:
with timeout of 600 seconds -- ten minutes
move List_files to alias "Macintosh HD:Users:CK:Example:"
end timeout
The final script looks something like this:
tell application "Finder"
set TextFile to (choose file with prompt "Select your text file" of type {"txt"})
set My_Folder to (choose folder with prompt "Select your destination folder")
set List_files to paragraphs of (read TextFile as «class utf8»)
if the last item of the List_files = "" then set ¬
List_files to items 1 thru -2 of List_files
repeat with fp in List_files
set fp's contents to folder fp
end repeat
move List_files to My_Folder
end tell
The extra line that starts if the last item of... is just a safety precaution in case the last line of the text file is a blank line, which is often the case. This checks to see if List_files contains an empty string as its last item, and, if so, removes it; leaving it in would throw an error later in the script.
EDIT: Dealing with folders that don't exist
If the repeat loop throws an error due to an unrecognised folder name, then we can exclude that particular folder from the list. However, it's easier if we create a new list that contains only the folders that have been verified (i.e. the ones that didn't throw an error):
set verified_folders to {}
repeat with fp in List_files
try
set end of verified_folders to folder fp
end try
end repeat
move the verified_folders to My_folder
This also means we can delete the line beginning if the last item of..., as the check that this performs is now going to be caught be the try...end try error-catching block instead.

Related

AppleScript - Move all the files contained in subfolder to a top folder

I am looking for an edit to the current script. What I need is moving all the files from subfolders (recursively) in to one top folder, however if a file with the same name exist, create a new top-folder and continue there, this is what I have so far:
tell application "Finder"
try
set Random_name to random number from 100 to 9999
set theTopFolder to (choose folder)
set theFiles to a reference to every file of (entire contents of folder theTopFolder)
set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files"}
move theFiles to theNewFolder
on error
set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files" & Random_name}
move theFiles to theNewFolder
end try
end tell
Just to be clear the structure of the path is not:
Mainfolder/subfolder/file.xxx but Mainfolder/subfolder/sulbfolder2/subfolder3/....100/file.xxx so the script needs to work recursively which it does but it stops when a file exist with the same name
When a file with the same name exist my edit creates a new folder with Flattened Files+random number however when another file with the same name is moved the script stops for an error instead going ahead and creating a new Flattened Files+randonnumber folder. Any ideas?
Thank you
Your script isn't using recursion, it just lets the Finder get all the files. The additional error you are getting is because you are trying to move the whole list of files again.
One solution would be to step through the file items, testing for duplicates as you go, and make new folders as needed. The following script just moves duplicates to added folders (note that an error will still stop the script). I don't know how you are sorting the file list, so I included a line to uncomment to continue moving file items to the added folder.
set theTopFolder to (choose folder)
tell application "Finder"
set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files"}
set theFiles to every file of (entire contents of folder theTopFolder) as alias list
repeat with aFile in theFiles
if file ((theNewFolder as text) & (name of aFile)) exists then -- use added folders for duplicates
set counter to 1
set done to false
repeat until done
set suffix to text -2 thru -1 of ("000000" & counter) -- leading zeros for sorting
set alternateFolder to (theTopFolder as text) & "Flattened Files" & space & suffix
tell me to (do shell script "mkdir -p " & quoted form of POSIX path of alternateFolder) -- make new folder as needed
if file (alternateFolder & ":" & (name of aFile)) exists then -- continue to next one
set counter to counter + 1
else
move aFile to folder alternateFolder
# set theNewFolder to folder alternateFolder -- uncomment to continue moving here after a duplicate
set done to true
end if
end repeat
else
move aFile to folder (theNewFolder as text)
end if
end repeat
end tell

"Tag and move" Applescript no longer works (High Sierra)

Firstly, let me stress that I have almost no Applescript experience. I'm an Oracle developer by trade, so please assume my knowledge is ZERO so I'd be grateful if you could really dumb down your response.
I wrote this script a year or so ago and it has suddenly stopped working. I'm guessing that a macOS upgrade (on High Sierra) no longer tolerates my probably poorly written script.
on run {input, parameters}
repeat with theFile in input
set FileName to theFile as text
tell application "Finder"
if FileName ends with "-xs.jpg" then
--label value, 0 is no label, 1 Orange, 2 Red, 6 Geen
set the label index of file FileName to 6
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:basket-[xs]:" with replacing
else if FileName ends with "-sm.jpg" then
set the label index of file FileName to 1
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:thumbnails-[sm]:" with replacing
else if FileName ends with "-lg.jpg" then
set the label index of file FileName to 2
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:main-[lg]:" with replacing
else if FileName ends with "-xlg.jpg" then
set the label index of file FileName to 5
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:large-[xlg]:" with replacing
end if
end tell
end repeat
return input
end run
The error I get is "The action "Run AppleScript" encountered an error: "Finder got an error: Can't set file "Macintosh HD:Users:Karla:Pictures:1-IMAGES-TO-DO:image1-lg.jpg" to 2."
If I comment out the tagging and try to just do the move, I get "The action "Run AppleScript" encountered an error: "Finder got an error: Can't get folder "Mackintosh HD:Users:Karla:Pictures:FTP:main-[lg]:"."
Edit:
I have also tried:
on run {input, parameters}
repeat with the_input_file in input
set FileName to POSIX file (the_input_file as alias)
end repeat
return input
end run
but get the error The action "Run AppleScript" encountered the error: "Can't get POSIX file (alias "Macintosh HD:Users:Karla:Pictures:file.jpg")."
Edit again:
So this is where I am. I've created a droplet as follows:
on open theDroppedItems
set lg_folder to POSIX path of "Macintosh HD:Users:Karla:Pictures:test1:"
repeat with current_item_cnt from 1 to count of theDroppedItems
-- load the next file in the_file
set the_current_file to item current_item_cnt of theDroppedItems
move file the_current_file to lg_folder
end repeat
end open
And I still get a -1728 error onthe file. "Can’t get file (alias \"Macintosh HD:Users:Karla:Pictures:test1:test-lg.jpg\")." number -1728 from file (alias "Macintosh HD:Users:Karla:Pictures:test1:test-lg.jpg")
I've spent 2 days on a script that used to work and now inexplicably does not in amongst trying to do my real job. This is supposed to make my life easier.
Try using this code for your droplet...
property folderXS : "Macintosh HD:Users:Karla:Pictures:FTP:basket-[xs]"
property folderSM : "Macintosh HD:Users:Karla:Pictures:FTP:thumbnails-[sm]"
property folderLG : "Macintosh HD:Users:Karla:Pictures:FTP:main-[lg]"
property folderXL : "Macintosh HD:Users:Karla:Pictures:FTP:large-[xlg]"
on run
-- Executed when the script is launched
set theFiles to choose file with prompt ¬
"Choose Files" multiple selections allowed true ¬
without showing package contents
repeat with theFile in theFiles
set FileName to theFile as text
tell application "Finder"
if FileName ends with "-xs.jpg" then
--label value, 0 is no label, 1 Orange, 2 Red, 6 Green
set the label index of file FileName to 6
move FileName to folder folderXS with replacing
else if FileName ends with "-sm.jpg" then
set the label index of file FileName to 1
move FileName to folder folderSM with replacing
else if FileName ends with "-lg.jpg" then
set the label index of file FileName to 2
move FileName to folder folderLG with replacing
else if FileName ends with "-xlg.jpg" then
set the label index of file FileName to 5
move FileName to folder folderXL with replacing
end if
end tell
end repeat
return theFiles
end run
on open theDroppedItems
-- Executed when files are dropped on the script
set lg_folder to "Macintosh HD:Users:Karla:Pictures:test1"
repeat with current_item_cnt from 1 to count of theDroppedItems
set the_current_file to item current_item_cnt of theDroppedItems
tell application "Finder"
move file the_current_file to lg_folder
end tell
end repeat
end open
If anybody comes here as I did, looking for an answer, I can give you an inelegant, hacky way to at least get this working. I had variable this_item which contained an HFS file which I wanted to move into todaysFolder.
Part of the problem is Finder doesn't always know what to do with POSIX paths involving variables, and sometimes you need to use the "my" keyword first. Other time, you need to leave it out. I couldn't figure out the logic.
The following ridiculous code block does it reliably and seems to catch every strange, inscrutable exception.
try
move my (POSIX file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
try
move (POSIX file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
try
move (file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
move (file (this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
end try
end try
end try

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

Applescript to copy each file individually to target folder

I have all these movies in .dvdmedia format and I want to covert them all to a smaller file size such as .mp4.
But what I need to do is create an applescript that will copy the individual file to a folder 'Conversion'. Once the file in the folder is deleted it copies the next item and deletes the previous.
I've completed an Automation script that once the item is added to the folder is starts formatting the file through TurboHD then deletes the file and moves the converted item to another folder 'Completed'
Does anyone able to help me with this?
Please note that the location of the movies are on a NAS drive
there :) I coded the following. Please note to save it as an Application with Stay open after run handler checked.
You have to set the source and the target path to the paths in your environment.
Finally you have to set the return value. The value sets the interval in seconds to wait until next execution. If each of your conversions takes about an hour, I think I would check every 5 minutes meaning the handler has to return 300.
-- The idle-Handler defines a repetitive task
-- Note: Save as Application with option "Stay open after run handler"
on idle
-- define the folders to watch
set theSourceFolder to (POSIX file "/Users/myHomeFolder/Desktop/Conversion_Source") as alias
set theTargetFolder to (POSIX file "/Volumes/myMountedVolume/Conversion") as alias
-- check the contained files (get visible files only because of .DS_Store etc.)
tell application "System Events"
set availableSourceFiles to every file of theSourceFolder whose visible is true
set filesOfTargetFolder to files of theTargetFolder whose visible is true
end tell
-- if no more source file is available, quit this script
if (count of availableSourceFiles) = 0 then
quit
end if
-- if the target folder is empty start move
if (count of filesOfTargetFolder) = 0 then
-- get the first item from source folder
set sourceFile to (first item of availableSourceFiles) as alias
-- use the Finder to copy the file
tell application "Finder"
-- duplicate the file to the target folder
duplicate sourceFile to theTargetFolder
-- move the source file to trash after copy
move sourceFile to trash
end tell
end if
-- the integer returned is the time to wait (in seconds)
-- here: two minutes
return 120
end idle
Enjoy, Michael / Hamburg

Create new folder from files name and move files

(This is a new edit from a previous question of mine which achieved -3 votes. Hope this new one has a better qualification)
I need to create an Automator service to organize a high amount of files into folders. I work with illustrator and from each .ai file I create 3 more formats: [name.pdf], [name BAJA.jpg] and [name.jpg], thats 4 files in total
My problem is that during the week I repeat this process to more than 90 different .ai files. So 90 files * 4 is 360 independent files all into the some project folder.
I want to grab all 4 related files into one folder, and set the folder name as the same as the .ai file.
Since all the file names are identical (except one), I thought of telling the finder to grab all the files with the same name, copy the name, create a folder and put this files inside, but I have a file name variant [name LOW.jpg] Maybe I can tell the script to strip that work as an exception.
That way I will all 4 the files unified into one folder.
Thank you in advance
Update: This problem was originally posted back in 2013, now I have a solution. People help me assembled this script to fit my needs.
I added this as a service and assigned a keyboard shurtcut on MacOs.
This is the code:
on run {input, parameters} -- create folders from file names and move
set output to {} -- this will be a list of the moved files
repeat with anItem in the input -- step through each item in the input
set {theContainer, theName, theExtension} to (getTheNames from anItem)
try
# check for a suffix and strip it off for the folder name
if theName ends with " BAJA" then
set destination to (makeNewFolder for (text 1 thru -6 of theName) at theContainer)
else
set destination to (makeNewFolder for theName at theContainer)
end if
tell application "Finder"
move anItem to destination
set the end of the output to the result as alias -- success
end tell
on error errorMessage -- duplicate name, permissions, etc
log errorMessage
# handle errors if desired - just skip for now
end try
end repeat
return the output -- pass on the results to following actions
end run
to getTheNames from someItem -- get a container, name, and extension from a file item
tell application "System Events" to tell disk item (someItem as text)
set theContainer to the path of the container
set {theName, theExtension} to {name, name extension}
end tell
if theExtension is not "" then
set theName to text 1 thru -((count theExtension) + 2) of theName -- just the name part
set theExtension to "." & theExtension
end if
return {theContainer, theName, theExtension}
end getTheNames
to makeNewFolder for theChild at theParent -- make a new child folder at the parent location if it doesn't already exist
set theParent to theParent as text
if theParent begins with "/" then set theParent to theParent as POSIX file as text
try
return (theParent & theChild) as alias
on error errorMessage -- no folder
log errorMessage
tell application "Finder" to make new folder at theParent with properties {name:theChild}
return the result as alias
end try
end makeNewFolder
Hope this helps.
It's a pity you get downvoted as I, personally, enjoy answering these sorts of questions, as it helps me practise and improve my own skills.
Thanks for posting your solution. I think it's a great gesture and others will find it useful.
This script is a bit shorter than and uses "System Events" instead of "Finder", so will be quicker for large numbers of files:
set IllustratorOutputFolder to "/Users/CK/Desktop/example"
tell application "System Events" to ¬
set ai_files to every file in folder IllustratorOutputFolder ¬
whose name extension is "ai"
set Output to {}
repeat with ai_file in ai_files
set AppleScript's text item delimiters to "."
get name of ai_file
get text items of result
set basename to reverse of rest of reverse of result as text
tell application "System Events"
get (every file in folder IllustratorOutputFolder ¬
whose name begins with basename)
move result to (make new folder ¬
in folder IllustratorOutputFolder ¬
with properties {name:basename})
end tell
set end of Output to result
end repeat
return Output -- list of lists of moved files
Just an alternative way of doing things. Not that it's better or worse, but just a different solution.
You could also save this as script.sh (in TextEdit in plain text mode) and run it with bash script.sh in Terminal:
cd ~/Target\ Folder/
for f in *.ai *.pdf *.jpg; do
dir=${f%.*}
dir=${dir% LOW}
mkdir -p "$dir"
mv "$f" "$dir"
done

Resources