Trying to print new folder names to a text edit/numbers file when logged (AppleScript) - automation

I'm trying to add new folders added to a drive onto a textEdit or numbers file so that there's an up to date list of what projects I have active on individual drives.
I'm very new to AppleScript so I don't know what my limitations are, but I basically just need to figure out how to append to the end of the file (it seems like textEdit would be simplest) with the name of the new folder. I currently have:
on adding folder items to theAttachedFolder after receiving theNewItems
-- Get the name of the attached folder
tell application "Finder"
set theName to name of theAttachedFolder
-- Count the new items
set theCount to length of theNewItems
-- Display an alert indicating that the new items were received
activate
display alert "Attention!" message (theCount & " new items were detected in folder. Adding to TextEdit file.")
end repeat
end tell
Any help is much appreciated. Thank you!

The File Read/Write suite in the StandardAdditions scripting dictionary has open for access and write commands that can be used to append to a text file (the AppleScript Language Guide also has a command reference), and AppleScript's text item delimiters or string concatenation can be used to assemble a string from the list of file items.
There are some older topics describing ways to write to a file, but in the following example I've separated the main stuff from the folder action handler so that it can also be called from the run handler for testing in the Script Editor:
property logFile : "/path/to/output/textfile.txt" -- HFS or POSIX
on run -- test
set folderItems to (choose file with multiple selections allowed)
tell application "Finder" to set theFolder to container of first item of folderItems
doStuff(theFolder, folderItems)
end run
on adding folder items to theAttachedFolder after receiving theNewItems
doStuff(theAttachedFolder, theNewItems)
end adding folder items to
to doStuff(theFolder, theItems)
set folderItems to ""
activate
display alert "Attention!" message "" & (count theItems) & " new items were detected in folder." & return & "Adding to log file."
tell application "Finder" to set folderName to name of theFolder
repeat with anItem in theItems
tell application "Finder" to set newName to name of anItem
set folderItems to folderItems & tab & newName & return
end repeat
writeToFile(logFile, "Items added to " & folderName & ":" & return & folderItems & return)
end doStuff
to writeToFile(someFile, someText)
try
set theOpenFile to (open for access someFile with write permission)
write someText to theOpenFile starting at eof -- append
close access theOpenFile
on error -- make sure file is closed
try
close access theOpenFile
end try
end try
end writeToFile

Related

Using AppleScript to programmatically create an AppleScript file in plain text format

I have an AppleScript that is used to programmatically create a test script file in one of these Office 2016 app folders:
~/Library/Application Scripts/com.microsoft.Excel
~/Library/Application Scripts/com.microsoft.Word
~/Library/Application Scripts/com.microsoft.Powerpoint
This is the test.scpt file content which is programmatically generated:
on handlerTest(thisPhrase)
say thisPhrase
end handlerTest
This test.scpt file contains a single handler which speaks the phrase passed to it.
When the script is created in one of these folders, I cannot see the content of the script file in Finder and calling the handler from a Microsoft Office app using the new VBA AppleScriptTask causes the Office app to crash. I think the script is being created as a byte-compiled file because it cannot be viewed in Finder as plain text.
If I then copy the script file generated programmatically by my script creator script to the Documents folder, the plain-text content of the script is viewable in Finder.
Now, if I copy the script file from the Documents folder back to the corresponding com.microsoft folder (without modifying it), I can now see the plain-text content in Finder and calling the handler using the VBA AppleScriptTask function works as expected. I don't understand how the format is apparently changing due to copy/paste actions?
How can I programmatically create the script file in the com.microsoft.xyz folder in plain text format?
Here is my VBA procedure:
Sub TestScript()
AppleScriptTask "test.scpt", "handlerTest", "hello world"
End Sub
Here is my example script creator script which programmatically creates a test.scpt file in the com.microsoft.Powerpoint scripting folder: (kudos to eliteproxy for the original source script)
property theFolders : {"~/Library/'Application Scripts'/com.microsoft.Powerpoint"}
try
tell application "Finder" to set targetFolder to (target of the front window) as alias
on error -- no window
set targetFolder to (choose folder)
end try
# build a parameter string from the folder list
set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, space}
set {theFolders, AppleScript's text item delimiters} to {theFolders as text, tempTID}
do shell script "cd " & quoted form of POSIX path of targetFolder & "; mkdir -p " & theFolders
--Write the Script file if it does not exist
if ExistsFile("~/Library/'Application Scripts'/com.microsoft.Powerpoint/test.scpt") is false then
tell application "Finder"
--GET THE WORKING DIRECTORY FOR FILE COPY OF SCRIPT
get folder of (path to me) as Unicode text
set workingDir to POSIX path of result
--Write the new script in the current working directory
set textFile to workingDir & "test.scpt"
--Delete script if it exists
set posixPath to POSIX path of textFile as string
do shell script "rm -rf \"" & posixPath & "\""
--Create Script Interface file for Microsoft PowerPoint VBA Applications
set fd to open for access textFile with write permission
-- Create test handler which speaks the passed phrase parameter
write "on handlerTest(thisPhrase)" & linefeed to fd as «class utf8» starting at eof
write "say thisPhrase" & linefeed to fd as «class utf8» starting at eof
write "end handlerTest" & linefeed to fd as «class utf8» starting at eof
close access fd
--Copy the script file into the MACOS-Specific 'safe' folder
set fromPath to quoted form of POSIX path of (workingDir) & "test.scpt"
set toPath to quoted form of "~/Library/'Application Scripts'/com.microsoft.Powerpoint"
do shell script "cp -R " & fromPath & space & "~/Library/'Application Scripts'/com.microsoft.Powerpoint" with administrator privileges
end tell
end if
--Delete the temp script file from the working directory
set posixPath to POSIX path of textFile as string
do shell script "rm -rf \"" & posixPath & "\""
--Provide confirmation
set theAlertTitle to "TEST"
set theAlertMsg to "The script has been successfully installed."
display alert theAlertTitle message theAlertMsg as informational buttons {"OK"} default button "OK" cancel button "OK"
--For use when checking if a file exists
on ExistsFile(filePath)
tell application "System Events" to return (exists disk item filePath) and class of disk item filePath = file
end ExistsFile
I could be wrong in my interpretation of your question, but it appears as if you are looking to create file “Test.scpt” with your handler “handlerTest” as the code, in a folder named “com.microsoft.Excel” (for example). If that is all you are looking to achieve, I believe this solution should work for you...
script theHandler
on handlerTest(thisPhrase)
say thisPhrase
end handlerTest
end script
storeScript()
on storeScript()
set thisScript to store script theHandler in (path to home folder as text) ¬
& "Library:Application Scripts:com.microsoft.Excel:Test.scpt" replacing yes
end storeScript

Mac OS app based on Applescript

I'm new to Xcode as well as I am to AppleScript
All I need is to run an AppleScript in an Xcode application.
Bassically, the application is downloading pictures from a url list in Excel and renames the files acording the list in Excel
Here is the applescript code :
tell application "Microsoft Excel"
set filenames to value of every cell of range "K3:K200" of sheet "Image_Moves" of document 1
set URLs to value of every cell of range "L3:L200" of sheet "Image_Moves" of document 1
end tell
repeat with i from 1 to count URLs
if (item i of filenames is not missing value) and (item i of URLs is not missing value) then
set thisFname to quoted form of (POSIX path of ({path to desktop, "Image_Moves:"} as text) & item i of filenames)
set thisUrl to quoted form of item i of URLs
set status to (do shell script "curl -s -o " & thisFname & space & thisUrl)
end if
end repeat
try
tell application "Finder"
delete (every item of folder ("Image_Moves") whose name begins with "0")
end tell
on error
display dialog ("Error. Couldn't Move the File") buttons {"OK"}
end try
In Xcode, you can write a full application in AppleScript with the "Cocoa-AppleScript" template. Also, you can compile and execute an AppleScript with the NSAppleScript class. If your question is just about making an AppleScript executable, use Save As... in Script Editor and save your AppleScript as an application.
HTH

Not able to save to a created folder (applescript)

so I have been trying to create a script that will create a folder on my desktop, then create a spreadsheet, and save the spreadsheet to said folder. here is the script...
set folderName to "Tester"
set FileName to "MayDay"
set SaveName to FileName & ".numbers" as string
set FilePath to "Macintosh HD:Users:Ryan:Desktop:" & FileName & ":"
tell application "Finder" to make new folder at desktop with properties {name:folderName}
tell application "Numbers" to activate
tell application "Numbers" to make new document with properties {name:FileName}
tell application "Numbers"
tell document 1
tell table 1 of sheet 1
merge range "B8:C8"
end tell
end tell
delay 1
tell application "Numbers" to activate
end tell
tell application "Numbers" to (save document 1) in FilePath
end
It has no problem making the folder, opening the spreadsheet, changing its name, and merging the cells, the problem comes in at the end when I try to save it.
I have tried adding (as numbers) no parenthesis after the save command, that errors out. After I run the script, and clear the crash, I can close out numbers and it will prompt me to save it in the "Tester" folder, but it won't do it on its own. insert grey hairs and headaches here.
I am really new to applescript, and I am hoping this is just a simple syntax thing, any help would be appreciated.
Thanks in advance!
R
Here's working code. A key is to use POSIX path and POSIX file and also the "save ... in ..." takes a file reference, not a string.
set folderName to "Tester"
set fileName to "MayDay.numbers"
set FilePath to (path to desktop as string) & folderName & ":" & fileName
set posixPath to POSIX path of FilePath
try
tell application "Finder" to make new folder at desktop with properties {name:folderName}
on error errMsg
end try
tell application "Numbers"
set myDoc to make new document with properties {name:fileName}
tell myDoc
tell table 1 of sheet 1
merge range "B8:C8"
end tell
end tell
delay 1
save myDoc in POSIX file posixPath
end tell

Embed Applescript in Global Field to (Export Container and Trigger Printing with Acrobat)

I am trying to tie together a filemaker script that will export PDFs to a temporary space and use and apple script to print them.
I was able to cull together info from this and some other boards to create an applescript that will print the PDFs using Acrobat from a folder.
I have already created a script that finds the Related attachments and exports them to the desktop.
What I'm having trouble with is merging the two.
I need to export the PDF to a folder or temporary place and trigger the apple script to initiate the printing...
This great Suggestion was provided by Chuck of chivalrysoftware.com/…...
Calculate the location to export by appending the filename to Get( TemporaryPath ).
Export the container field contents to FileMaker to that path.
Save the path to a global field in FileMaker
Use an embedded AppleScript to access the global field path
Use AppleScript to open the file in Preview and print it
This is my apple script:
set myFolder to (path to desktop folder as text) & "Print:"
set myfiles to list folder myFolder without invisibles
repeat with myfile in myfiles
set mycurrentfile to ((myFolder as string) & (myfile as string)) as string
batchprint(mycurrentfile)
end repeat
on batchprint(mycurrentfile)
tell application "Adobe Acrobat Pro"
activate -- bring up acrobat
open alias mycurrentfile -- acrobat opens that new file
tell application "System Events"
tell process "Acrobat"
click menu item "Print..." of menu 1 of menu bar item "File"¬
of menu bar 1
click button "Print" of window "Print"
tell application "System Events"
tell process "Acrobat"
click menu item "Close" of menu 1 of menu bar item "File"¬
of menu bar 1
end tell
end tell
end tell
end tell
end tell
tell application "Finder" -- to move the printed file out
set x to ((path to desktop folder as text) & "Printed PDFs:")
if alias x exists then
beep
else
make new folder at the desktop with properties {name:"Printed PDFs"}
end if
move alias mycurrentfile to folder "Printed PDFs"
end tell
end batchprint
My Filemaker script is:
Go to Related Record[
Show only related records; From table: 'Attachments";
Using layout: "Attachements Report' (Attachments); New window
]
Enter Find Mode
Constrain Found Set [Restore]
Sort Records [Restore; No dialog]
# After finding the related attachments and constraining them to the specific type
# we rename and export them to the desktop
Go to Record/Request/Page [First]
Loop
Set Variable [$Path; Value:
Get ( DesktopPath ) & Attachments::Record number & "-"
& Attachment Type List 2::Prefix_z & Lien::Lien_ID_z1]
Export Field Contents [Attachments::file_c; $Path]
Go to Record/Request/Page [Next: Exit after last]
End Loop
Close Window [Current Window]
First of all, the FileMaker part. Create a global text field in one of your tables. It looks like the Attachments table would be the best place for it. I'll call it g_applescript_parameter for this.
Now we're going to use your $Path variable, which given the calc you've provided should be something like /Aslan/Users/chuck/Desktop/1234-ABC4321. I'd recommend appending a .pdf to the end of it since you'll be exporting PDF files. This may help later.
Also, I would recommend that you use Get( TemporaryPath ) instead of Get( DesktopPath ). Anything you place in the temporary folder will be automatically deleted when you quit FileMaker, which means you don't have to write anything to clean up the desktop folder later and you don't have to manually trash them either. Let FileMaker do that work for you. :)
Regardless, FileMaker uses a path of the form filemac:/volumeName/directoryName/fileName (see the notes in the Specify output file dialog box for the Export Field Contents script step). So you should also prepend filemac: to the beginning of your path variable.
All told, your $Path should be set to something like this:
"filemac:" & Get( DesktopPath ) & Attachments::Record number & "-" &
Attachment Type List 2::Prefix_z & Lien::Lien_ID_z1 & ".pdf"
So your export path for FileMaker should work better now. But AppleScript requires a different format for the path to the same file. Given the above, AppleScript's version should be something like /Users/chuck/Desktop/1234-ABC4321.pdf. In other words, everything after the drive name. Fortunately FileMaker can get the drive name with the Get( SystemDrive ) function. For me that function returns /Aslan/. So if we take the $Path variable as defined above and remove filemac: and the name of the drive as defined by Get( SystemDrive ) and add an extra slash at the beginning, that would convert our FileMaker path into an AppleScript path:
"/" & Substitute( $Path; "filemac:" & Get( SystemDrive ); "" )
Use Set Variable to create an $ASPath variable and set it to the above.
Now within your loop store the contents of the $ASPath variable within that global text field:
Loop
Set Variable[ $Path; …]
Set Variable[ $ASPath; …]
Set Field[Attachments::g_applescript_parameter; $ASPath)
Export Field Contents[Attachments::file_c; $Path]
Go to Record/Request/Page[Next; Exit after last]
End Loop
Now AppleScript can extract that information. I'm assuming that given an accurate file being passed to the batchprint function, batchprint will work, so keep that, but remove everything before it and use something like this:
set _pdf_path to contents of cell "g_applescript_parameter" of current layout
batchprint(_pdf_path)
on batchprint(mycurrentfile)
...
end batchprint
Add a Perform AppleScript step after the Export Field Contents step and place the above code in it.
Note that the first line of the above AppleScript will only work as written from within FileMaker. If you're testing this outside of FileMaker in, for example, Script Editor, then you'll need to make that first line read
tell applicaiton "FileMaker" to set _pdf_path ...
You don't need to do this within the Perform AppleScript script step because by default commands are sent to the enclosing FileMaker application.

How can I create a display dialog that presents specific file path options for a given PDF file?

I am very new to using Automator and Applescript.
I would like to use Automator and AppleScript to detect PDF files that are downloaded to the "Downloads" folder and opens a display dialog that allows me to select the file path and move the file. So far, what I have (which isn't right) is something like:
set question to display dialog "Save fileName in..." buttons {"Figuring Relation", "Iconoclasm", "Elsewhere"} default button 3
set answer to button returned of question
if answer is equal to "Figuring Relation" then
tell application "Finder" to move fileName to POSIX file "/Users/mac/Documents/College/Junior/Fall/Art 347 - Figuring Relation"
I want the "Figuring Relation" and "Iconoclasm" buttons to change the file path to a designated file path (I don't want to browse for it), and the "Elsewhere" button to open a Finder window where I can select/browse the path.
If possible, I'm also looking to add the date to the beginning of the file name as "mm-dd_filename".
I am not sure of how to translate the Automator Input to Applescript, or how to include the filename in the display dialog text. Thank you so much for any help.
Here is an example using just applescript. In my example, it assumes you're selecting the file you're wanting to move, but you could easily add something for the script to "Find" all files ending with ".pdf" if you wanted to and then loop through the results.
on run
try
set thisFile to choose file
tell application "Finder" to set currentName to thisFile's name
-- Setting variables for the destinations to be used later
set FiguringRelationPath to (path to documents folder) & "College:Junior:Fall:Art 347 - Figuring Relation:" as string
set IconoclasmPath to (path to documents folder) & "Iconoclasm:" as string
-- Ask the user
set answer to button returned of (display dialog "Save \"" & currentName & "\" in..." buttons {"Figuring Relation", "Iconoclasm", "Elsewhere"} default button 3)
-- Set the destination variable based on the users response to the dialog
if answer is equal to "Figuring Relation" then
set destination to FiguringRelationPath
else if answer is equal to "Iconoclasm" then
set destination to IconoclasmPath
else
set destination to choose folder with prompt "Please select the destination folder" as string
end if
-- Test that the destination directory exists, if not post the error
try
set destination to destination as alias
on error
error ("Destination path " & destination as string) & " doesn't appear to exist"
end try
-- Rename the file with the date prefix
set tDatePrefix to (do shell script "date '+%m-%d'") & "_" as string
tell application "Finder" to set x's name to tDatePrefix & x's name as string
-- Move the file
tell application "Finder" to move thisFile to destination
on error err
activate
display dialog "Error: " & err buttons {"OK"} default button 1
end try
end run