Delete all files in one folder via Apple Script - applescript

I worked out two scripts to do that, but none of them is working (I even don't get shown the "on error" message. Maybe it's because of the pre-defined folder as a variable? As for simplicity and a cleaner code I didn't want to write the complete path again, so I used that folder variable. In case it is relevant, the DataHubFolder variable was defined like this earlier: set DataHubFolder to cloudDocs & "Current Projects:Data Hub:"
Here are the codes I used:
Code #1:
try
tell application "Finder"
set f to every file ¬
of folder ¬
of DataHubFolder & "Distrokid:"
delete f
end tell
on error
display dialog ("Error. Couldn't move the file") buttons {"OK"}
end try
Code #2:
try
tell application "Finder"
delete (every item of folder (DataHubFolder & "Distrokid:"))
end tell
on error
display dialog ("Error. Couldn't move the file") buttons {"OK"}
end try
Would be so happy about some tips.
Thanks a lot.

Related

Apple Script runs more than once when file is opened

I have a piece of code which is used as a folder action and constantly watches the folder. When a new file is placed in the folder, the script runs and outputs a dialog box. The user can either open or print the file from the dialog box. However, when I select the open button, the code then produces the dialog box again when the a new file hasn't been opened. This only occurs when the file is opened and not when it is printed.
Can anyone help? Code is below
on adding folder items to theAttachedFolder after receiving theNewItems
set filepath to theNewItems as string
if filepath contains "HA" then
set theDialogText to "HA is in file name"
do shell script "afplay '/System/Library/Sounds/Submarine.aiff'"
display dialog theDialogText buttons {"Dismiss", "Print", "Go to "} default button "Go to order" with icon note
if result = {button returned:"Go to"} then
tell application "Finder"
open file filepath
end tell
else if result = {button returned:"Print"} then
tell application "Shelf Label Printer"
activate
print filepath
quit
end tell
display dialog "Printed" with icon note
end if
if filepath contains "OG" then
set theDialogText to "OG is in file name"
do shell script "afplay '/System/Library/Sounds/Submarine.aiff'"
display dialog theDialogText buttons {"Dismiss", "Print", "Go to"} default button "Go to order" with icon note
if result = {button returned:"Go to"} then
tell application "Finder"
open file filepath
end tell
else if result = {button returned:"Print"} then
tell application "Shelf Label Printer"
activate
print filepath
quit
end tell
display dialog "Printed" with icon note
Edit: Mojave is running on the iMac in question.
There were a few problematic points in this code, any of which could produce odd behavior, so I cleaned it up so that it works correctly on my machine. New code first, then bullet points on what I changed...
on adding folder items to theAttachedFolder after receiving theNewItems
repeat with thisItem in theNewItems
set filepath to POSIX path of thisItem as string
if filepath contains "HA" or filepath contains "OG" then
set theDialogText to "HA or OG is in file name"
do shell script "afplay '/System/Library/Sounds/Submarine.aiff'"
tell application "System Events"
display dialog theDialogText buttons {"Dismiss", "Print", "Go to"} default button 3 with icon note
end tell
if result = {button returned:"Go to"} then
tell application "System Events"
open file filepath
end tell
else if result = {button returned:"Print"} then
tell application "Shelf Label Printer"
activate
print filepath
quit
end tell
display dialog "Printed" with icon note
end if
end if
end repeat
end adding folder items to
"after receiving" always gives a list of aliases, even if it's a single item, so we should loop through the list rather than trying to convert it directly to string.
You duplicated the same code for 'HA' and 'OG' files, so I merged them
Your Display Dialog cited the default button as "Go to order" when your buttons were "Dismiss", "Print", "Go to". That was throwing an error (Display Dialog wants an exact match to one of the buttons). I replaced that with the index 3.
Folder Actions and the Finder do not always play well together, so I switched to the System Events app for the dialogs and the file open procedure.
This should work properly now...

Applescript: on adding folder items to; renaming files without the loop

I created a droplet which would allow me to rename files from an input box.
on adding folder items to este_folder after receiving este_file
display dialog "what's their name?" default answer ""
set text_returned to text returned of the result & ".jpg"
display dialog text_returned
tell application "Finder"
set the name of file este_file to text_returned
end tell
end adding folder items to
It works fine, but it creates a loop where I have to hit cancel again to stop the script, as it thinks a new file has been added. I would like to just rename it once; and then not have the second dialog box pop up again. I have tried rerouting the file to another folder:
on adding folder items to este_folder after receiving este_file
display dialog "what's their name?" default answer ""
set text_returned to text returned of the result & ".jpg"
display dialog text_returned
tell application "Finder"
set the name of file este_file to text_returned
end tell
repeat with anItem in este_file
tell application "Finder"
set destFolder to "Macintosh HD:Users:maxwellanderson:Desktop:BetterinTexas" as alias
move anItem to folder destFolder
end tell
end repeat
end adding folder items to
But that doesn't work either-it doesn't process the renaming portion of the script. Any suggestions on what I should do to get rid of the second dialog box?
The script is being called twice because renaming the file within the watched folder is—for all intents and purposes—like adding a new file into the folder. Therefore, it's called once when the file is actually added; and called a second time when it's renamed.
Moving the file as you suggested will work, but you have to move the file before you rename it. Therefore, shove the code that moves the file near the top of the script, then the renaming bits at the bottom.
As a side-note, I notice you have a repeat with loop to handle multiple file moves, but only one statement that handles a single file renaming. One of these is not like the other. If this watched folder received multiple files at the same time, it would most likely rename them all to the same name, thus potentially over-writing multiple files. If the watched folder only ever receives one file at a time, anyway, then the repeat with loop is redundant.
This code is modelled on yours and will handle a single file move-and-rename (but not a group of files—or, more accurately, as I stated above, it would rename multiple files to the same name, thus overwriting all but the last one in the list):
on adding folder items to este_folder after receiving este_file
set destFolder to POSIX file "/Users/maxwellanderson/Desktop/BetterinTexas" as alias
set text_returned to text returned of ¬
(display dialog "what's their name?" default answer "") ¬
& ".jpg"
display dialog text_returned
tell application "Finder" to ¬
set the name of ¬
(move file este_file to destFolder) ¬
to text_returned
end adding folder items to
If you need it to handle multiple files, then you can wrap everything from set text_returned to to text_returned in a repeat with loop as you've done in your second code block. This will sequentially bring up dialog boxes—one per file—and move/rename the files accordingly.
If you have any questions, or need clarification, leave a comment and I'll get back to you.

Directing an app to run off of a different script in AppleScript.

I'm making an applescript to help with school. You type the subject you wish to access, and then it opens that folder (inside the app). However, some subjects have ebooks, so I want there to be another dialog box asking you wether you want to open the ebook or the folder. Unfortunately, a display dialog can't branch off of another display dialog.
So far, the only way I've found around this is to direct the app to run off of another script (in the "Scripts" folder of the app). I've tried
tell application "Script Editor" to run script (path to me as sting) & "Contents:Resources:Scripts:Subject.scpt"`
But it didn't work. Sorry if I'm barking up the wrong tree and seem completely stupid. Thanks
As far as I understood what you're trying to achieve, the following script would work.
set listOfSubjects to {"Math", "Biology", "History", "Languages"}
set subjectsWithEbook to {"Biology", "History"}
choose from list listOfSubjects with prompt "Select the subject"
set subject to item 1 of result
set openEbook to false
repeat with subjectItem in subjectsWithEbook
if subjectItem contains subject then
choose from list {"Open folder", "Open Ebook"} with prompt "What to open?"
set openType to item 1 of result
if openType contains "Open Ebook" then
set openEbook to true
end if
exit repeat
end if
end repeat
if openEbook then
--Open ebook
else
--Open folder
end if
I am guessing that you want to type the subject name? Here is an example that uses dialog boxes.
set subjectFolderPath to (path to me as string) & "Contents:Resources:Subjects:"
set subjectsWithEbook to {"English", "Spanish"}
display dialog "What subject would you like to access?" default answer ""
set theSubject to text returned of the result
if theSubject is in subjectsWithEbook then
display dialog "Would you like to open the Folder or the Book?" buttons {"Folder", "Book"} default button 1
set toOpen to button returned of the result
if toOpen is "Book" then
-- tell app "Preview" to open ???
beep
else
tell application "Finder" to open folder (subjectFolderPath & theSubject & ":")
end if
else
tell application "Finder" to open folder (subjectFolderPath & theSubject & ":")
end if
You might also want to have a list of subjects that are allowed and error check for them.

What is the correct syntax for the `add` command in AppleScript's library for Automator?

Goal
I would like to use AppleScript to open Automator and add specific actions to a new Workflow, regardless of the localization settings (language). In other words, I would like to use AppleScript to open a new Automator workflow and add specific actions in a specific order (at indexes) using the bundle identifiers of each action (to avoid language issues) or some other way to avoid language issues.
The Problem
The problem is that I cannot get Automator to add anything to the workflow.
What is the syntax for the add command?
Can I use bundle ids to add actions?
So far, this is what I have:
tell application "Automator"
make new workflow with properties {name:"Merge PDF Files"} -- Skips Opening Dialog
add "Get Specified Finder Items" to workflow 1 at index 1 --("com.apple.Automator.SpecifiedFiles")
add "PDF-Seiten kombinieren" to workflow 1 at index 2 --("com.apple.action.joinpdf")
end tell
Complete Code for a Merge PDF Files Droplet
After bwaldie posted his answer, I would like to share my useful droplet. You can put it on any Mac running OS X (especially useful for people who aren't familiar with Automator). To use it, just paste the code into the AppleScript Editor and save it as an application.
See code for droplet:
on open the_Droppings
-- CONVERT INPUT LIST OF ALIASES TO POSIX PATHS
repeat with itemStep from 1 to count of the_Droppings
set item itemStep of the_Droppings to POSIX path of item itemStep of the_Droppings
end repeat
tell application "Automator"
activate
set theWorkflowName to "Merge PDF Files"
set msg to "no"
tell application "Finder" to if exists POSIX path of ((path to temporary items as string) & theWorkflowName & ".workflow" as string) as POSIX file then set msg to "yes"
if msg is "no" then
set myWorkflow to make new workflow with properties {name:theWorkflowName, path:POSIX path of ((path to temporary items as string) & theWorkflowName & ".workflow" as string)}
add (first Automator action where its id = "com.apple.Automator.SpecifiedFiles") to myWorkflow at index 1
add (first Automator action where its id = "com.apple.action.joinpdf") to myWorkflow at index 2 --("com.apple.Automator.SpecifiedFiles")
else
set myWorkflow to open POSIX path of ((path to temporary items as string) & theWorkflowName & ".workflow" as string)
end if
set actionsList to name of Automator action of myWorkflow
set firstAction to item 1 of actionsList
tell myWorkflow
set value of setting of Automator action firstAction to the_Droppings -- MUST BE LIST OF POSIX PATHS
end tell
end tell
end open
Try something along the lines of...
set theWorkflowName to "Merge PDF Files"
tell application "Automator"
set myWorkflow to make new workflow with properties {name:theWorkflowName, path:POSIX path of ((path to desktop folder as string) & theWorkflowName & ".workflow" as string)}
save myWorkflow
add (first Automator action where its id = "com.apple.Automator.SpecifiedFiles") to myWorkflow
end tell
I think the key is to create the workflow, then save it, and then add the action.
Hope this helps!
-Ben
If you want to use Automator, there is no need for scripting. This works for me:
start Automator;
create new Service or e.g. create new Workflow;
if you created a Service, select "Service receives PDF files in
Finder.app" at the top of the window; if you chose Workflow, select
Files & FOlders in the list of Actions on the left and drag Get
Selected Finder Items to the right and make sure that Appending Pages is selected;
Select PDFs in the Actions list and drag Combine PDF Pages to the right
Select Files and Folders in the Actions list and drag Copy Finder Items to the right and make sure that Desktop is selected
Drag "Make Finder Item Names Sequential" to the right, select Make Sequential" and "Add number to existing item name".
You may want to tweak and experiment with Automator a bit to make sure that it does exactly what you want.

AppleScript "Save As" HTML in TextEdit

I want AppleScript to loop through a set of of RTF files in folder and save them as HTML files.
This is my simple code so far. The XXXX is where I'm struggling:
tell application "Finder"
set source_folder to choose folder
set aList to every file in source_folder
repeat with i from 1 to number of items in aList
tell application "TextEdit"
set aFile to (item i of aList)
save as aFile XXXXXXXXX
end tell
end repeat
end tell
I'm really new to this... any help much appreciated.
You don't need TextEdit for this. There is a command line program textutil which will do the job without all the opening and saving stuff required with TextEdit. We can fix your TextEdit script (it has a few errors) but try this first and let us know if it does the job for you. The html files will have the same name but with the html extension and will be located in source_folder. The ouput path can be changed in the code by using the "-output" switch of textutil. See "man textutil" if you want to look at everything it can do.
And a general question... what is a RTD file? Do you mean rtf or rtfd? Textutil will work with rtf/rtfd but not rtd, so I hope that isn't really your file type.
set source_folder to choose folder with prompt "Choose a source folder."
set output_folder to choose folder with prompt "Choose an output folder."
tell application "Finder"
set theFiles to (files of entire contents of source_folder) as alias list
end tell
repeat with aFile in theFiles
tell application "Finder"
set fileName to name of aFile
set fileExt to name extension of aFile
end tell
set outputPath to (output_folder as text) & text 1 thru -((count of fileExt) + 1) of fileName & "html"
do shell script "/usr/bin/textutil -convert html -output " & quoted form of POSIX path of outputPath & space & quoted form of POSIX path of aFile
end repeat
You mention you are new to applescript, so I'll give you some general pointers you should keep in mind when writing applescript code.
Avoid putting tell blocks of code inside each other. You have tell app TextEdit inside tell app Finder. That's bad. Doing this is a source of many conflicts because you are basically telling the Finder to tell TextEdit to do something. That's not good because commands can get confused and it's really hard to debug these kinds of issues. So keep your tell blocks separate.
Avoid telling an application to perform a command that is not in its applescript dictionary. You should only tell an application to do commands that it knows and an application only knows about the commands in its dictionary. So for example, you are telling the Finder to "choose folder". The Finder does not know that command. That's an applescript command. So doing as you have done is another possible source of errors. In this case that's a simple command and it will work but in general avoid doing this.
Regarding the Finder, you should avoid using it too much. The Finder is a major program on your computer and is often busy doing computer related stuff. As such it's best to only use it when necessary. As an example you can see in my code that I removed the "choose folder" and the repeat loop from the Finder. I purposely appended "as alias list" to the end of the Finder command to make the list of files usable outside of the Finder tell block of code. Of course use the Finder if needed but it's best to not use it if you don't need it.
Use the applescript dictionary of your applications. As mentioned above, the dictionary lists all of the terms and the syntax that an application understands (granted the dictionaries are difficult to understand but you will get better at it the more you use them). Under the file menu of AppleScript Editor choose "Open dictionary" and a list of all the applications that understand applescript is shown. Choose an application from that to see its dictionary. So for example, you are trying to figure out TextEdit's "save as" command. You can usually get good direction from the dictionary so you should take a look at that. Use the search field to search!
So I hope that helps! Good luck.

Resources