Applescript to copy each file individually to target folder - applescript

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

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

Moving entire folders with 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.

applescript, folder action, move copied items fails, timing issue?

Please help, I can't think of a fix for this.
A folder action is meant to do this for each file copied into a folder:
Derive a subfolder name, and a new filename.
Create subfolder.
Move file into it.
Rename subfolder and file.
Files are copied from a different volume and are usually 500…1500 MB.
Problem: The moving step (step 3) in the folder action script fails if the files are that large and their number is >1
and they are copied from a different volume.
The script works fine when copying: small files, or from the same volume, or only one file.
In a test, all of 200 Alias' were correctly processed, but only 23 of 512. This is not a problem, the number of added_items is usually <10 and unlikely to ever be >50. But it may help targeting the issue.
I suspected a timing issue, but all attempts to fix it using generous timeout's didn't work.
The script (note - before trying, set the regex in the do shell script lines to something workable):
on adding folder items to this_folder after receiving added_items
repeat with the_item in added_items
with timeout of 3600 seconds
tell application "Finder"
if kind of the_item is not "Folder" then
repeat -- wait until item is copied. Thanks to original coder on the WWW.
set {size:fileSize, busy status:Busy} to (info for (the_item))
if not Busy and (fileSize is greater than 0) then exit repeat
delay 1
end repeat
with timeout of 600 seconds
set new_folder_name to do shell script "echo '" & (name of the_item) ¬
& "' | sed -E 's/llooongRegex/replace/g'"
set new_item_name to do shell script "echo '" & (name of the_item) ¬
& "' | sed -E 's/otherRegex/replace/g'"
set new_folder to (make new folder at this_folder with properties {name:(new_folder_name & "-temp")}) as alias -- "-temp" in case new folder and file will have the same name
move file the_item to folder new_folder -- <== fails if ((added_items >1) AND (files big, tested with 0.5…1.5GB) AND (copied from different volume)) ==> Timing issue?
set name of (first item of (get contents of new_folder)) to new_item_name
set name of new_folder to new_folder_name
end timeout
end if
end tell
end timeout
end repeat
end adding folder items to
P.S.: is folder-action frequent enough for a tag?
After replacing the repeat -- wait until item is copied.... clause with a simple delay 60, the script works. So it is a timing problem.
Waiting for the target folder to stop changing size as describe here works as long as only 1 file copying (bunch of files dropped) is running. Two or more drag'n drops, and it hiccups again (nice word, #vadian!).
Ditto when checking for the size of individual added items to remain constant.

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 : How to get files in folder without hidden files?

I actually have two questions.
How to exclude hidden files like .DS_STORE, Icon when I try to get files in folder ?
I've tried "without invisibles" but it seems not working.
How to set my var the_new_folder as an existing folder if already exists ?
Thanks for answers.
My code:
--
-- Get all files in a selected folder
-- For each file, create a folder with the same name and put the file in
--
tell application "Finder"
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
end tell
on file_to_folder(the_folder)
tell application "Finder"
-- HELP NEEDED HERE
-- HOW TO EXCLUDE HIDDEN FILES (Like Icon, .DS_STORE, etc)
set the_files to files of the_folder
repeat with the_file in the_files
-- Exclude folder in selection
if kind of the_file is not "Folder" then
set the_path to container of the_file
set the_file_ext to name extension of the_file
-- Remove extension of the file name
set the_file_name to name of the_file as string
set the_file_name to text 1 thru ((offset of the_file_ext in (the_file_name)) - 2) of the_file_name
-- Make the new folder with the file name
try
set the_new_folder to make new folder at the_path with properties {name:the_file_name}
on error
-- HELP NEEDED HERE
-- HOW TO SET the_new_folder AS THE EXISTING FOLDER
end try
-- Move the file in the new folder
move the_file to the_new_folder
end if
end repeat
end tell
end file_to_folder
tell application "Finder"
(display dialog ("It's done!") buttons {"Perfect!"})
end tell
Using the System Events context instead of Finder:
bypasses the problem with the AppleShowAllFiles preference[1]
is much faster in general.
Using the visible property of file / folder objects in the System Events context allows you to predictably determine either all items, including hidden ones (by default), or only the visible ones (with whose visible is true):
# Sample input path.
set the_path to POSIX path of (path to home folder)
tell application "System Events"
set allVisibleFiles to files of folder the_path whose visible is true
end tell
Simply omit whose visible is true to include hidden files too.
The code for either referencing a preexisting folder or creating it on demand is essentially the same as in the Finder context:
# Sample input path.
set the_path to POSIX path of (path to home folder)
# Sample subfolder name
set the_subfolder_name to "subfolder"
tell application "System Events"
if folder (the_path & the_subfolder_name) exists then
set subfolder to folder (the_path & the_subfolder_name)
else
set subfolder to make new folder at folder the_path ¬
with properties {name: the_subfolder_name}
end if
end tell
[1] In order to predictably exclude hidden items, a Finder-based solution is not only cumbersome but has massive side effects:
You need to determine the current state of the the AppleShowAllFiles preference (defaults read com.apple.Finder AppleShowAllFiles),
then turn it off.
then kill Finder to make the change take effect (it restarts automatically) - this will be visually disruptive
then, after your code has run, restore it to its previous value.
then kill Finder again so that the restored value takes effect again.
I believe that your first question is not a problem. Your code works fine for me.
As for the second issue, the simplest method is to use the text representation of the_path, and simply build the new folder, and see if it already exists:
set the_path_Text to (the_path as text)
set try_Path to the_path_Text & the_file_name
if (folder try_Path) exists then
set the_new_folder to (folder try_Path)
else
set the_new_folder to make new folder at the_path with properties {name:the_file_name}
end if
If you are truly having difficulty with the first code section, please post a new question with more details, such as a copy of the Result section of the Script.
Thank you to all of you ! #mklement0 #craig-smith
You will find below the corrected code with your help!
If I share this code, you want to be cited for thanks?
--
-- Get all files in a selected folder
-- For each file, create a folder with the same name and put the file in
--
-- Get user folder
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
on file_to_folder(the_folder)
tell application "System Events"
-- Get all files without hidden
set the_files to files of the_folder whose visible is true
repeat with the_file in the_files
-- Remove extension of the file name
set the_file_ext to name extension of the_file
set the_file_name to name of the_file as string
set the_file_name to text 1 thru ((offset of the_file_ext in (the_file_name)) - 2) of the_file_name
-- Make a new folder or get the existing
set the_path to POSIX path of the_folder
if folder (the_path & the_file_name) exists then
set the_new_folder to folder (the_path & the_file_name)
else
set the_new_folder to make new folder at folder the_path with properties {name:the_file_name}
end if
-- Move the file to the new folder
move the_file to the_new_folder
end repeat
end tell
end file_to_folder
-- Ending dialog
display dialog ("It's done!") buttons {"Perfect!"}

Resources