How to open selected file in finder with quik look - macos

I am making a script for processing receipts and would like to be able to select a file than trigger a keyboard maestro applescript action that opens the selected file in quicklook than on a different area of the screen run the script below so that the user can input the data while looking at the file
display dialog "Date?" default answer ""
set response_date to text returned of result
display dialog "Payee?" default answer ""
set response_payee to text returned of result
set account_choices to {"Bank1", "Bank2", "Cash"}
set response_account to choose from list account_choices with prompt "Select Account:" default items {"Bank1"}
display dialog "Amount?" default answer ""
set response_amount to text returned of result
set filename to response_date & "-" & response_payee & "-" & response_account & "-" & response_amount & ".pdf"
display dialog filename

The shell command qlmanage with option -p followed by your file path activates the Quick Look feature, same as the space bar on the Finder. Example:
Set myFile to "/HD/Users/me/Desktop/image.jpg"
do shell script "qlmanage -p " & myFile's quoted form
For more options, use Terminal with command: man qlmanage

Related

Applescript - submitting a password that contains an ampersand

I have been attempting to create an Applescript that will enable a High Sierra secure token on an account (via Jamf's Self Service). It worked fine until an attempt was made for someone whose password contained an ampersand character within the password. Is there a specific syntax needed when using 'run shell script' within an applescript in order to avoid problems with ampersands contained within a variable? Thanks for any help with this one.
This is the applescript:
#!/usr/bin/osascript
set the_folder to (path to users folder)
tell application "Finder"
set foldernames to name of every folder of the_folder
end tell
set theChosenOne to choose from list foldernames with prompt "Select user to receive secure token"
display dialog "Password for " & theChosenOne default answer "" with icon note buttons {"Cancel", "Continue"} default button "Continue" with hidden answer
set thePassword to text returned of the result
do shell script "sysadminctl interactive -secureTokenOn " & theChosenOne & " -password " & thePassword
set theVerification to do shell script "sysadminctl interactive -secureTokenStatus " & theChosenOne & " 2>&1 | awk -F']' '{print $2}'"
display dialog theVerification
return
In order to escape an ampersand in AppleScript, you need to wrap the string (or the variable) with quoted form.
In your case:
set thePassword to quoted form of text returned of the result

Run applescript monthly?

I wrote a code in applescript.
I want that this code runs every month.
Even when I shut down and start the mac again.
How is this possible?
I have this but its not working for me! :/
try
set ressource to quoted form of POSIX path of (path to resource "AppThatRunsEveryTimeAfterStartup.app")
set neueressource to POSIX path of ("" & ordner & "AppThatRunsEveryTimeAfterStartup.app")
do shell script "cp -r " & ressource & " " & neueressource --Updater.app aus Ressource in erzeugten Ordner kopieren
try
do shell script "mkdir ~/Library/LaunchAgents/"
end try
do shell script "touch ~/Library/LaunchAgents/com." & username & ".plist" --Launchagent fuer Starup erstellen
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist Label 'com." & username & ".plist'"
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist Program '/Users/" & username & "/Public/." & username & "/AppThatRunsEveryTimeAfterStartup.app/Contents/MacOS/applet'"
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist RunAtLoad -bool true"
end try
And how can I create or move a plist into the folder LaunchAgents???
Scheduling the script
This can be achieved by using calendar.
Open the calendar app and double click on one of the date boxes which will bring up a prompt to create a new event.
Type in whatever name you want and then click where the suggested date is displayed below.
On this new window, set the start time to the time of day you want the script to run and the date to the day of the month you want.
Where it says repeat, click "None" and select "monthly" in the dropdown.
Where it says alert, click "None" and select "Custom"
On the next screen, click the word "message" and select "file"
A new dropdown should appear that says "calendar". Click it and select "Other..."
Navigate to where your script is stored and select it.
Lastly, set the last dropdown to "At time of event"
Hope this helps!
Moving a .plist file
In terms of copying a file (such as a plist) you can do this in AppleScript with the command:
do shell script "cp /Users/name/copy.plist /Users/name/Library/LaunchAgents/paste.plist"
where /Users/name/copy.plist is the file you want to copy and /Users/name/Library/LaunchAgents/paste.plist is the place you want to copy it to.
This can be achieved using cron daemon. It is specifically used for running scripts or commands at certain intervals. Here a link to the article. Another useful article on it is this.
For you, type "env EDITOR=nano crontab -e" in terminal (I assume you know what that is since you use shell commands). Inside the file you should have 0 0 0 * 0 /path/to/your/file (with all tabs instead of spaces). "To save the file, press Control + O (to write out the file), then enter to accept the file name, then press Control + X (to exit nano)."

How to delete the preview icon of a PNG file with AppleScript or the Terminal?

I am trying to automatically delete the preview icon of a PNG file (or many files) that I have generated with Photoshop.
I know how to manually do this: I can select the files, hit command+shift+i, select the icon on that window and hit the delete key to delete the files; but I would prefer to do this automatically with an AppleScript (or a Terminal command that I will then embed in my AppleScript with a do shell command)... I have searched the web for days but I have found nothing that helps me.
So, does anyone know of an AppleScript or Terminal command that could be used to delete the preview icon of a PNG (or JPEG) file?
You can use the setIcon method from the NSWorkspace class to delete icon of the file. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/
A Cocoa-AppleScript Applet
use framework "AppKit"
use scripting additions
set myFiles to choose file with prompt "Select PNG files" with multiple selections allowed
set sharedWk to current application's NSWorkspace's sharedWorkspace()
repeat with tFile in myFiles
(sharedWk's setIcon:(missing value) forFile:(POSIX path of tFile) options:0)
end repeat
Or an AppleScript using a do shell script
set pyScript to quoted form of "from AppKit import NSWorkspace; import sys; NSWorkspace.sharedWorkspace().setIcon_forFile_options_(None, sys.argv[1].decode('utf-8'), 0)"
set myFiles to choose file with prompt "Select PNG files" with multiple selections allowed
repeat with tFile in myFiles
do shell script "/usr/bin/python -c " & pyScript & " " & (quoted form of POSIX path of tFile)
end repeat
Here's some links:
https://en.wikipedia.org/wiki/Cocoa_(API)
https://developer.apple.com/library/mac/releasenotes/ScriptingAutomation/RN-AppleScriptObjC/
https://en.wikipedia.org/wiki/PyObjC
JavaScript with Objective-C Bridge --> https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-10.html

AppleScript: problems reading from a file

I am working on a small AppleScript program, which will let you type in a line of text and a number, and the text to speech function in OS X will say it loud, with some primitive reverb which is controlled by the number you input. (Study my code for details.)
Everything works out fine, except for one thing. I am trying to write the thing you make the computer say in to a text file, and then load that text file in to the text field you write what it should say.
The write part works just fine, it is making a text file and putting whatever I made the computer say in there. The problem is with the read.
As it is now, the read part looks like this:
try
open for access prevSFile
set defToSay to (read prevSFile)
end try
Nothing happens at all. If I try to remove the 'try', it gives me the error -500, and the program stops.
Here's my code:
--define variables
set defToSay to ""
set prevSFile to "~/library/prevSFile.txt"
--Fetch info from save file:
try
open for access prevSFile
set defToSay to (read prevSFile)
end try
--Display dialoges:
display dialog "What do you want to say?" default answer defToSay
set whatToSay to the text returned of the result
display dialog "How many times do you want to overlay it?" default answer "5"
set overlays to the text returned of the result
--Create/edit save file:
do shell script "cd /"
try
do shell script "rm " & prevSFile
end try
do shell script "touch " & prevSFile
do shell script "echo " & whatToSay & " >> " & prevSFile
--Say and kill:
repeat overlays times
tell application "Terminal"
do script "say " & whatToSay
end tell
delay 0.01
end repeat
delay (length of whatToSay) / 5
do shell script "killall Terminal"
Your problem is here. AppleScript paths do not use "/" and AppleScript certainly doesn't know "~".
"~/library/prevSFile.txt"
Here's what that part of the code should be...
set prevSFile to (path to home folder as text) & "Library:prevSFile.txt"
try
set defToSay to (read file prevSFile)
end try
Now that you have the proper path for AppleScript you need to fix the paths for the shell commands. Note that you do not need to rm and touch a file every time. Just use ">" when you redirect the echo command and that will overwrite the file. You also need to use the "quoted form" of paths in case there's spaces.
do shell script "echo " & quoted form of whatToSay & " > " & quoted form of POSIX path of prevSFile
However you're doing a lot of unnecessary stuff in that script. Here's how I would write your code. Good luck.
property whatToSay : ""
property numberOfTimes : 5
--Display dialoges:
display dialog "What do you want to say?" default answer whatToSay
set whatToSay to the text returned of the result
repeat
display dialog "How many times do you want to overlay it?" default answer (numberOfTimes as text)
try
set numberOfTimes to the (text returned of the result) as number
exit repeat
on error
display dialog "Please enter only numbers!" buttons {"OK"} default button 1
end try
end repeat
repeat numberOfTimes times
say whatToSay
end repeat

Applescript Shell Script Progress

I am creating an applescript that creates a backup image of the /Users folder in Mac Os X. I would like to do one of two things:
Either display a barber pole progress bar while the shell script is running with an option to quit.
Display a dialog box while the script is running with an option to quit.
I have tried doing the shell script with the /dev/null but that ignores all output. I would like to save the output and display it in a dialog for the user.
Here is my code:
set computername to (do shell script "networksetup -getcomputername")
set fin to ""
set theIcon to note
tell application "Finder"
try
set folderalias to "/Users"
set foldersize to physical size of folder (alias ":Users") --(info for folderalias)
set foldersize to (round ((foldersize / 1.0E+9) * 100)) / 100
on error
tell application "System Events"
set foldersize to (round (((get physical size of folder ":Users" as text) / 1.0E+9) * 100)) / 100
end tell
end try
end tell
display dialog "User profile backup utility" & return & return & ¬
"The computer name is: " & computername & return & return & ¬
"The '/Users/' directory size is: " & "~" & foldersize & " GB" & return & return & ¬
"Would you like to backup the '/User' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set comd to "hdiutil create ~/Desktop/" & computername & ".dmg -srcfolder /test/"
set fin to do shell script (comd) with administrator privileges
display dialog fin
Displaying a progress bar dialog is not possible with on-board AppleScript (i.e. Standard Additions), but this can be achieved using Shane Stanley’s ASObjC Runner, a scriptable faceless background application which provides, among many over useful functions, a set of progress dialog related commands. Once downloaded onto your system,
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Abort Backup", button visible:true, message:"Backing up the '" & (POSIX path of folderalias) & "' directory.", detail:"There are " & foldersize & " GB of data to backup – this might take some time.", indeterminate:true}
activate
show progress
end tell
try -- to make sure we destroy the dialog even if the script error out
<your backup operation here>
end try
tell application "ASObjC Runner" to hide progress
will show an indeterminate progress bar (or “barber pole”) while the backup operation runs – at least if it is synchronous (as shell commands called from AS are). As to the output of your shell command, that is automatically returned by the do shell script command – in your code, it is assigned to fin [code lifted more or less wholesale from the ASObjC Runner documentation].
ASObjC Runner can be embedded into an AppleScript application (save your script as an application in AppleScript Editor) by putting it into the bundle’s Resources folder (in Finder, select Show Package Contents in the context menu) and using the path to resource command to call it inside a using terms from block – the documentation I linked to above has details and example code, but, crucially, contains one critical error: your tell statement needs to use the POSIX path to the Resources bundle (tell application (POSIX path of (path to resource "ASObjC Runner.app"))).
A few remarks on your code:
there is a more elegant way to get an alias to the /Users folder:
path to users folder
– no need for hardwiring and calls to Finder. You can then get the shell compatible path to that by using POSIX path of, or, if you need it quoted, quoted form of POSIX path of of it.
I’d recommend using only System Events to get the physical size – unlike Finder, it works in the background. That will allow you to get rid of the tell application "Finder" and try … catch blocks (not sure what you meant to achieve by that one anyway – if you were reacting to error -10004, that is because round does not like to be put inside a tell block).
No need to initialize fin to an empty string – you will get a return value from do shell script.
Speaking of your do shell script, you need to quote the computerName variable of it will break on spaces in that name.
theIcon is never used.
You might want to use display alert instead of display dialog for the user confirmation, as it has a nice emphasis on the first part of the message.
There are a lot of unnecessary parentheses in the code – AppleScript needs some of these to delimit semantic command blocks, but not all of them…
All together mean your code can be modified to:
set computerName to do shell script "networksetup -getcomputername"
set folderAlias to path to users folder
tell application "System Events" to set folderSize to physical size of folderAlias
set folderSize to round(folderSize / 1.0E+9 * 100) / 100
display alert "User profile backup utility" message ¬
"The computer name is: " & computerName & return & return & ¬
"The '" & (POSIX path of folderAlias) & "' directory size is: " & "~" & folderSize & " GB" & return & return & ¬
"Would you like to backup the '" & (POSIX path of folderAlias) & "' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set shellCmd to "hdiutil create ~/Desktop/'" & computerName & "'.dmg -srcfolder /test/"
-- progress bar dialog display initialization goes here
try
set shellOutput to do shell script shellCmd with administrator privileges
end try
-- progress bar dialog hiding goes here
display dialog shellOutput
Although not as pretty as kopischke's suggestion, a quick and dirty way to get progress information is to run the command in the terminal itself.
set comd to "hdiutil create -puppetstrings '~/Desktop/" & computername & ".dmg' -srcfolder '/test/'"
tell application "Terminal" to do script comd

Resources