Applescript Shell Script Progress - shell

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

Related

AppleScript - Copying Folder Content shows error - Download & UnZip Works

UPDATE01: The cleaned Up code - Zip download was removed and current issue is that the 'Copy' command gets executed before 'unzip' is completed; resulting in a copy of an empty folder over to the destination folder. when running as an .app but when running as a script in AppleScriptEditor.. it runs fine :/
property DownloadsFolder : path to downloads folder
property appSupport : path to application support from user domain
property ZIPName : "ResourcesOffline.zip" -- downloaded ZIP file
property AppName : "MyApp" -- name of App in Application Support
property ExtractedFolderName : "MyContent" -- name for folder in Downloads where ZIP is saved
property ExtractedFolderPath : ((DownloadsFolder as text) & ExtractedFolderName & ":")
property DataFolder : ":UserBottle:FFApp:D_C:PData:LP:App:Data"
-- inform user of process --
display dialog "
IMPORTANT:
Before running this App, please be sure you have downloaded the 'ResourcesOffline.zip', and it is in your 'Downloads' Folder.
Press [OK] when you are ready to start.
" buttons {"Ok"}
-- Set up DSResources folders in Downloads and User's Bottle --
do shell script "mkdir -p " & quoted form of (POSIX path of ExtractedFolderPath) & space & quoted form of POSIX path of {(appSupport as text) & AppName & (DataFolder as text) & ":DSResources"}
display dialog "Check! Directories in Downloads and Data" buttons {"Ok"}
-- Extract to the folder created in Downloads --
try
do shell script "unzip -u " & quoted form of POSIX path of ((DownloadsFolder as text) & ZIPName) & " -d " & quoted form of POSIX path of ExtractedFolderPath
on error
display dialog "
Process failed.
Could not find 'ResourcesOffline.zip' in 'Downloads' folder.
Please be sure that the file exists in the specified location.
" buttons {"Quit"} with icon 0
if button returned of the result is "Quit" then error number -128
end try
display dialog "Check! UnZipped in MyContent" buttons {"Ok"}
-- Copy items to the folder created in Application Support --
tell application "Finder"
set SourceFolder to folder (ExtractedFolderPath as text)
set DestinationFolder to folder ((appSupport as text) & AppName & (DataFolder as text))
duplicate (entire contents of first folder of SourceFolder) to DestinationFolder with replacing
display dialog "
All content was copied successfully. Thank you!
" buttons {"Ok"}
end tell
display dialog "Check! All done - About to Delete TEMP Extracted files" buttons {"Ok"}
do shell script "rm -rf " & quoted form of POSIX path of ExtractedFolderPath
quit
==========================================================================
I am new to scripting, in general. Carry a basic understanding, but not much of a programmer.
I am trying to write an AppleScript script to do the following:
Download 'XXX.ZIP' from 'http://MyLink.com/XXX.zip'
Download in 'Downloads' folder and overwrite any existing file if it already exists
Show a progress bar of the download (<- I know a progress bar is tough, so this is a nice to have
Once downloaded, unpack the ZIP in same 'Downloads' location
Once Unzipped: I will have this (this is what is in the ZIP already):
One Main Folder [001]
One SubFolder in MainFolder [001A]
One File in MainFolder 001B.txt
Up till here all works fine; however from this point onwards I am struggling
Copy 'All Contents' of MainFolder (not the main folder itself; just the subfolder and text file in it) from 'Downloads' folder to 'Library/Application Support/MyApp/Resources' and Replace any existing files
Once copied, display popup dialogue that 'process is completed' - [OK]
Notes:
I am using ~/Folder locations because this script is for anyone to use, so I can't hard code the full path i.e: MacHD/Users/USERNAME/Downloads .. etc
PS - I am new to coding; so a lot of things in this code may seem 'senseless'; but I am trying so please bare with me. I have gone through a lot of forums to derive what I have but Gods of coding aren't happy with me… I am having issues trying to make all this work; this is the script I have till now:
set newFolderPath to quoted form of (expandPath("~/Downloads/MYCONTENT"))
set cmdStr to "if [[ ! -d " & newFolderPath & " ]]; then
mkdir -m 755 " & newFolderPath & "; fi"
do shell script cmdStr
on expandPath(pPathStr)
local fullPath
set fullPath to pPathStr
if fullPath = "~" then
set fullPath to (POSIX path of (path to home folder))
else if fullPath starts with "~/" then
set fullPath to (POSIX path of (path to home folder)) & text 3 thru -1 of fullPath
end if
return fullPath
end expandPath
-- Download --
tell application "Finder"
do shell script "curl -L -o ~/Downloads/MYCONTENT/SOME_RESOURCES.ZIP 'https://MyWebsite.com/Stuff/DownloadableContent/SOME_RESOURCES.ZIP' > ~/Downloads/MYCONTENT/status 2>&1 &"
set fileSize to 0
set curTransferred to 0
set curProgress to 0
repeat until curProgress = "100"
try
set lastLine to paragraph -1 of (do shell script "cat ~/Downloads/MYCONTENT/status")
set curProgress to word 1 of lastLine
set fileSize to word 2 of lastLine
set curTransferred to word 4 of lastLine
tell me
display dialog "Downloading; Please wait, this will take a while.
Status: " & curTransferred & " of " & fileSize & " (" & curProgress & "%)" buttons {"Refresh", "cancel"} giving up after 5
if the button returned of the result is "cancel" then return
end tell
on error
display dialog "Download failed. To restart the download, please press the 'Retry' button" buttons {"Quit", "Retry"} with icon 0
end try
end repeat
set theDialogText to "Download is complete. Press [OK] to continue"
display dialog theDialogText
-- Extract --
do shell script "unzip -u ~/Downloads/MYCONTENT/SOME_RESOURCES.ZIP -d ~/Downloads/MYCONTENT/"
do shell script "/bin/sleep 10"
-- ** FROM HERE ONWARDS I AM GETTING AN ERROR **
-- Copy --
set DownloadFolder to "~/Downloads/MYCONTENT/RESOURCES/"
set DestinationFolder to "~/Library/Application Support/MYAPPLICATION/RESOURCES/"
copy every file of folder (DownloadFolder's entire contents) to folder DestinationFolder
set theDialogText to "All content has been copied. Thank you!"
display dialog theDialogText
end tell
Your outline and script example are a bit different, so I went with the outline:
Create folders in the user's Downloads and Application Support folders as needed
Download a zip file to the folder created in Downloads and extract it to that folder - the zip file contains a main folder containing a sub folder (or folders) containing files
Copy the entire contents of the main folder to the Resources folder in the folder created in Application Support for the application
There are a few ways to do a progress bar or download status using some AppleScriptObjC, but for better control those should probably be done from an application.
The main problems with your script are that the Finder does not understand POSIX paths, and you missed creating the folder structure in Application Support. There are standard commands to get paths to the various system folders, so string manipulations aren't needed to get the script to work on other machines. In the following script, I keep track of the regular HFS paths, just coercing them to POSIX for the shell scripts, and added properties for the various names so they are in one spot.
property downLoads : path to downloads folder
property appSupport : path to application support from user domain
property webPage : "HTTPS://MYWEBSITE.COM/STUFF/DOWNLOADABLECONTENT/"
property webResource : "SOME_RESOURCES.ZIP" -- name for the downloaded file
property myApp : "MYAPPLICATION" -- name for folder in Application Support (bundle identifier would be better)
property baseName : "MYCONTENT" -- name for folder in Downloads
property basePath : ((downLoads as text) & baseName & ":")
-- Set up folders in Downloads and Application Support as needed --
do shell script "mkdir -p " & quoted form of (POSIX path of basePath) & space & quoted form of POSIX path of ((appSupport as text) & myApp & ":Resources")
-- Download and progress - more error handling is needed --
do shell script "curl -L " & quoted form of (webPage & webResource) & " -o " & quoted form of POSIX path of (basePath & webResource) & " > " & quoted form of POSIX path of (basePath & "status") & " 2>&1 &"
set fileSize to 0
set curTransferred to 0
set curProgress to 0
repeat until curProgress = "100"
try
set lastLine to paragraph -1 of (do shell script "cat " & quoted form of POSIX path of (basePath & "status"))
set curProgress to word 1 of lastLine
set fileSize to word 2 of lastLine
set curTransferred to word 4 of lastLine
tell me
display dialog "Downloading; Please wait, this will take a while.
Status: " & curTransferred & " of " & fileSize & " (" & curProgress & "%)" buttons {"Refresh", "Cancel"} giving up after 1
if the button returned of the result is "Cancel" then return
end tell
on error
display dialog "Download failed. To restart the download, please press the 'Retry' button" buttons {"Quit", "Retry"} with icon 0
if button returned of the result is "Quit" then error number -128
end try
end repeat
display dialog "Download is complete. Press [OK] to continue"
-- Extract to the folder created in Downloads --
do shell script "unzip -u " & quoted form of POSIX path of (basePath & webResource) & " -d " & quoted form of POSIX path of basePath -- Main Folder > Sub Folder > text file
-- Copy items to the folder created in Application Support --
tell application "Finder"
set downLoadFolder to folder basePath
set DestinationFolder to folder ((appSupport as text) & myApp & ":Resources")
duplicate (entire contents of first folder of downLoadFolder) to DestinationFolder with replacing -- contents of "Main Folder" -- 'duplicate' is the command to use for files
display dialog "All content has been copied. Thank you!"
end tell
Change the placeholder items in the properties as needed - Note that the shell scripts and web file names are case sensitive.

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

AppleScript - Change all app icons in a directory

I have folders containing applications. I want to be able to select the folder with an apple script, and have the script go through each app file in that directory, changing the icons for me.
I want to have the icon set from an image stored in the script directory.
I'd really appreciate any help because I've been trying to make this work for a while. This is my progress so far:
property appcurrentCount : 0
on run
set theFolder to (choose folder with prompt "Select the start folder")
doSomethingWith(theFolder)
end run
on doSomethingWith(aFolder)
tell application "Finder"
set subApps to every file of aFolder
repeat with eachFolder in subApps
-- replace icon here somehow
end repeat
end tell
display dialog "Count is now " & appcurrentCount & "."
end doSomethingWith
The script bellow does now what you want. As explained before, your icon file must be type icns. I now add this filter directly in the choose file command.
The selected icon will now replace ALL icons already in each Contents/Resources folder of all applications in the selected folder.
The replacement will be done preserving the name of the icns already in place.
Warning : there is no 'undo' command. your old icons are overwritten !!
set Myicon to choose file with prompt "Select Icns to be copied in every Application of the folder" of type "com.apple.icns"
set MyFolder to choose folder with prompt "Select the folder with all applications to be changed"
set Source to POSIX path of Myicon -- convert path to unix form
tell application "Finder"
set MyApps to every item of MyFolder whose name extension is "app"
display dialog "count apps=" & count of MyApps
repeat with anAps in MyApps -- loop for each App
set IcnFolder to ((anAps as string) & ":Contents:Resources:") as alias
set MyIcns to (every item of IcnFolder whose name extension is "icns")
display dialog "count of icn in " & alaps & " = " & (count of MyIcns)
repeat with oneIcon in MyIcns -- loop for each icns
set Destination to POSIX path of (oneIcon as string)
try
do shell script "cp " & (quoted form of Source) & " " & (quoted form of Destination)
end try
end repeat -- loop for each icns
end repeat -- loop for each App
end tell

Applescript an app to change background of notification centre in mountain lion

I wanted to create an app to change the background of the notification centre so applescripted it. Someone please tell me what's wrong with my code.
set NCBGPath to "/System/Library/CoreServices/Notification Center/Contents/Resources/"
set NCBackground to "linen.tiff"
set themeFolder to (choose folder with prompt "Choose a Theme") as text
set themePath to themeFolder & NCBackground
set posixNCPath to NCBGPath & NCBackground
set shouldCopy to false
tell application "Finder"
if exists file themePath then set shouldCopy to true
end tell
if shouldCopy then
do shell script "cp " & quoted form of POSIX path of themePath & space & quoted form of posixNCPath with administrator privileges
-- you probably should correct the file permissions too as the copied file probably won't have the proper owner and stuff
else
display dialog "Could not find the background file in the chosen folder."
end if
Possibly this: "If cp detects an attempt to copy a file to itself, the copy will fail."
What happens if you change the last if statement to:
if shouldCopy then
do shell script "cp " & quoted form of POSIX path of themePath & space & quoted form of NCBGPath with administrator privileges
-- you probably should correct the file permissions too as the copied file probably won't have the proper owner and stuff
else
display dialog "Could not find the background file in the chosen folder."
end if

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

Resources