Detect battery percentage with applescript - applescript

How would I detect what my computer's battery percentage is at and set it to a variable using applescript? All answers to similar questions say to install additional software, but I would like to do this with purely applescript. Is this possible? I've also tried searching through the applescript library with no success.

on run
set theBattString to (do shell script "pmset -g batt")
-- the above will return something like...
-- Now drawing from 'Battery Power' -InternalBattery-0 82%; discharging; 4:06 remaining
end run
Now you can parse theBattString to get the information you'd like from it.
Another option...
on run
do shell script "ioreg -l | grep -i capacity | tr '\\n' ' | ' | awk '{printf(\"%.2f%%\\n\", $10/$5 * 100)}'"
-- will output...
-- 79.63%
end run

The applescript unsigned variable can be used like a signed FileMaker variable... the ** can be removed I tried it Bold it
set batteryPercent to do shell script "pmset -g batt "
tell application "FileMaker Pro.app"
tell table "Power Test Results"
tell record 1
set cell "Test percentage via AppleScript Global" to batteryPercent
end tell
end tell
end tell

Thank ThrowBackDewd for his answer.
I made something a bit strange but it works for me.
Here is the AppleScript
[EDIT]
Here a more efficient code thanks to user #user3439894.
set batteryPercent to word 6 of paragraph 2 of (do shell script "pmset -g batt")
if batteryPercent < 40 then
beep
repeat 3 times
say "Attention " & batteryPercent & "%" & " before shut down."
display notification "Attention " & batteryPercent & "%" & " of charge before shut down." sound name "Glass"
end repeat
end if
idle application
on idle
set batteryPercent to word 6 of paragraph 2 of (do shell script "pmset -g batt")
if batteryPercent < 40 then
repeat 3 times
beep
say "Attention " & batteryPercent & "%" & " of charge before shut down."
display notification "Attention " & batteryPercent & "%" & " of charge before shut down." sound name "Glass"
end repeat
end if
return 60
end idle
[First post]
set theBattString to (do shell script "pmset -g batt")
-- the above will return something like...
-- Now drawing from 'Battery Power' -InternalBattery-0 82%; discharging; 4:06 remaining
set batteryLevel to splitText(theBattString, space)
--set totalItembatLvl to length of batteryLevel
set remainingTime to item 9 of batteryLevel
if remainingTime < "2:40" then
display alert "low battery " & remainingTime & " before shut down."
--batteryLevel & " " & remainingTime
end if
on splitText(theText, theDelimiter)
set AppleScript's text item delimiters to theDelimiter
set theTextItems to every text item of theText
set AppleScript's text item delimiters to ""
return theTextItems
end splitText
on getPositionOfItemInList(theItem, theList)
repeat with a from 1 to count of theList
if item a of theList is theItem then return a
end repeat
return 0
end getPositionOfItemInList
You can add it in an idle statement and check every minute for your battery level.
Any suggestions or corrections will be appreciated.
Regards.

Related

AppleScript that scrapes a website for data with curl function not working after some time making it

The code below used to work at scraping the trading value of a cryptocurrency website. Now it prints the name of the crypto and the time it was read but no value. Is it because the curl function isn't working anymore? Any help is appreciated.
The code uses a curl function to call the value of the crypto every 5 seconds. I got the code from a helpful stack overflow user and it worked well when I implemented it but it doesn't return the monetary value anymore. It creates a log file to the desktop and writes in the background as an application.
property eGrepBitcoinPrice : "priceValue\">\\$\\d{2},\\d{3}.\\d{2}"
property eGrepLitecoinPrice : "priceValue\">\\$\\d{2}.\\d{2}"
property eGrepDogecoinPrice : "priceValue\">\\$\\d{1}.\\d{5}"
property currentBitcoinPrice : missing value
property currentLitecoinPrice : missing value
property currentDogecoinPrice : missing value
property logToTextFile : missing value
on run -- Executed Only Once.. When This Script Applet Is Launched
activate
set logToTextFile to (display dialog ¬
"Enable Quick Log Mode?" buttons {"No", "Yes"} ¬
default button 2 with title "Log Mode")
if button returned of logToTextFile = "Yes" then
my logCommands's beginLog()
getPrices()
else
getPrices()
return {currentBitcoinPrice, currentDogecoinPrice, currentLitecoinPrice}
end if
end run
on idle
getPrices()
try
if button returned of logToTextFile = "Yes" then my logCommands's writeToLog()
on error errMsg number errNum
my logCommands's writeToLog()
end try
(* within this idle handler is where you will place
The bulk of your additional code. All of your Excel
Code Goes Here*)
return 5 -- In Seconds, How Often To Run Code In This Idle Handler
end idle
---------- PLACE ALL ADDITIONAL HANDLERS BENEATH THIS LINE ----------
on getPrices()
set currentBitcoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/bitcoin/markets/' " & ¬
"| grep -Eo " & quoted form of eGrepBitcoinPrice & " | cut -c 14-"
set currentLitecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/litecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepLitecoinPrice & " | cut -c 14-"
set currentDogecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/dogecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepDogecoinPrice & " | cut -c 14-"
end getPrices
on quit -- Executed Only When The Script Quits
if button returned of logToTextFile = "Yes" then my logCommands's endLog()
continue quit -- Allows The Script To Quit
end quit
script logCommands
property pathToPriceLog : POSIX path of (path to desktop as text) & "Price Log.txt"
on beginLog()
set startTime to ("Start Time... " & (current date) as text) & ¬
" Price Scanning At 5 Minute Intervals"
do shell script "echo " & startTime & " >> " & ¬
quoted form of pathToPriceLog
end beginLog
on writeToLog()
do shell script "echo " & "Bitcoin:" & quoted form of currentBitcoinPrice & ¬
" Dogecoin:" & quoted form of currentDogecoinPrice & ¬
" Litecoin:" & quoted form of currentLitecoinPrice & ¬
" " & quoted form of (time string of (current date)) & ¬
" >> " & quoted form of pathToPriceLog
end writeToLog
on endLog()
set endTime to quoted form of "End Time... " & (current date) as text
do shell script "echo " & endTime & " >> " & ¬
quoted form of pathToPriceLog
do shell script "echo " & " " & " >> " & ¬
quoted form of pathToPriceLog
end endLog
end script

Applescript Error: "Can’t make Can’t make some object into type some object."

I just updated to Catalina and one of my applescripts no longer works. Wondering if anyone has any ideas as to why? All of the folders selected (single or batch) are on a work server.
The result I get from the Script Editor after selecting a folder is:
-- 'ascr''err '{ '----':'utxt'("Can’t make Can’t make some object
into type some object."), 'errn':-1700,
'erob':'alis'("file:///System/Volumes/Data/data/ARLSCAN2/DIGI/ORIG/FRETSCHEL/Auto/DONE/F2509")
}
--Script Name:
set ScriptName to "jhoveValidation"
--Define user name
set userName to do shell script "whoami"
--Initalize ErrorCount
set errorCount to 0
--Initalize stampCount
set stampCount to 0
-- BEGIN SCRIPT!
--Option to change location mode
set locationModeChoice to display dialog "Would you like to check a single box folder or batch check a directory of box folders?" buttons ["Exit", "Single", "Batch"] default button 3 with title ScriptName with icon caution
set locationModeChoice to button returned of locationModeChoice
if locationModeChoice = "Exit" then
return
end if
if locationModeChoice = "Single" then
set imageDirectory to choose folder with prompt "Select Single Box Folder"
else if locationModeChoice = "Batch" then
set customFolder to choose folder with prompt "Please select a folder of box folders with standard ICT hierarchy:"
set masterFolder to customFolder
end if
-- BEGIN PREFLIGHT
--Populates list of files in finder
set progress description to "jhoveValidation"
set progress additional description to "Loading box and file information..."
set progress total steps to -1
delay 1
if locationModeChoice = "Batch" then
tell application "Finder"
set masterList to folders in masterFolder
if (count of items in masterList) is 0 then
display dialog "ERROR: No files were detected" buttons ["Quit"]
return
end if
end tell
else if locationModeChoice = "Single" then
set masterList to {}
set masterList to masterList & imageDirectory
end if
-- BEGIN IMAGE PROCESSING
set folderCount to count masterList
set folderCounter to 1
repeat with aFolder in masterList
set currentWorkingBox to getLastPathItem(aFolder)
tell application "Finder"
try
set inputFolder to (every folder in aFolder whose name begins with "TIFF") as alias
on error
display dialog "There was an error finding your TIFF folder for box:
" & currentWorkingBox & "
Please place the images you want to inspect in a completed box folder with a TIFF folder inside." buttons ["Quit"]
return
end try
end tell
set progress description to (currentWorkingBox as text) & ": jhoveValidation - Box " & folderCounter & " of " & folderCount
set progress additional description to "Loading TIFF files..."
set progress total steps to -1
tell application "Finder"
try
set filesList to files in inputFolder
set filesCount to count filesList
on error
display dialog "There was an error finding your TIFF folder for box:
" & currentWorkingBox & "
Please place the images you want to inspect in a completed box folder with a TIFF folder inside." buttons ["Quit"]
return
end try
end tell
--***BEGIN LOOP***
--Individual file processing begins here
set loggingCounter to 0
set totalSteps to count filesList
set progress total steps to totalSteps
repeat with aFile in filesList
set loggingCounter to loggingCounter + 1
log loggingCounter
set progress additional description to "Processing file " & loggingCounter & " of " & totalSteps
set progress completed steps to loggingCounter
set AppleScript's text item delimiters to "."
if (the last text item of (aFile as text) is "tif") then
tell application "Finder"
set theFile to aFile as alias
set theFilePath to POSIX path of theFile
log theFilePath
end tell
do shell script "cd ~/Desktop/jhove; ./jhove -c conf/jhove.conf -l SEVERE -o " & (theFilePath as text) & ".txt -m TIFF-hul " & theFilePath
else
end if
end repeat
set progress additional description to "Processing Results & Generating Reports..."
set progress total steps to -1
set currentWorkingFolderPath to POSIX path of (aFolder as alias)
try
do shell script "mkdir " & currentWorkingFolderPath & "VALIDATION"
end try
do shell script "mv " & currentWorkingFolderPath & "TIFF/*.txt " & currentWorkingFolderPath & "VALIDATION"
do shell script "grep -H 'Status' " & currentWorkingFolderPath & "VALIDATION/*.txt | sed 's/:/,/' > " & currentWorkingFolderPath & "VALIDATION/results.csv"
set theResults to {}
set theResults to theResults & paragraphs of (do shell script "cat " & currentWorkingFolderPath & "VALIDATION/results.csv")
set resultsCount to count theResults
set rejectList to {}
set reportStatus to "PASS"
set passCounter to 0
set failCounter to 0
repeat with aResult in theResults
set AppleScript's text item delimiters to ","
log text item 2 of aResult
set thisVar to text item 2 of aResult
if (text item 2 of aResult as text) = " Status: Well-Formed and valid" then
set passCounter to passCounter + 1
log "PASS"
else
set failCounter to failCounter + 1
set rejectList to rejectList & aResult
set reportStatus to "FAIL"
log "FAIL"
end if
end repeat
set totalCount to passCounter + failCounter
if reportStatus = "PASS" then
do shell script "echo \"All files have passed JHOVE Validation.\" > " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"" & passCounter & " files were validated.\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "date >> " & currentWorkingFolderPath & "jhoveReport.txt"
else
do shell script "echo \"!!! ATTENTION - some files have failed JHOVE Validation!!! \" > " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"" & passCounter & " files passed.\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"" & failCounter & " files failed.\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"----- \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"The following have reported failed JHOVE Validation: \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
repeat with aReject in rejectList
do shell script "echo \"" & aReject & "\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
end repeat
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"----- \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "date >> " & currentWorkingFolderPath & "jhoveReport.txt"
end if
set folderCounter to folderCounter + 1
end repeat
--***END LOOP***
-- END SCRIPT
-- Function: Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
end if
end repeat
return baseName
end getBaseName
on getLastPathItem(thePathToParse)
set thePathToParse to (thePathToParse as text)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to ":"
set lastPathLength to the number of text items in thePathToParse
set lastPathTarget to lastPathLength - 1
set the lastPathItemItem to text item lastPathTarget of thePathToParse
set AppleScript's text item delimiters to oldDelims
return lastPathItemItem
end getLastPathItem
on getLastPathItemFile(thePathToParse)
set thePathToParse to (thePathToParse as text)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to ":"
set the lastPathItemItem to the last text item of thePathToParse
set AppleScript's text item delimiters to oldDelims
return lastPathItemItem
end getLastPathItemFile

How to Mount Multiple EFI Partitions?

I’m trying to create an Applescript-Objc to mount multiple EFI partitions, but I’m not able to mount the EFI partitions on external drives only those on the internal disk,
what I've done so far is this:
set a to do shell script "diskutil list | grep EFI | grep -o -e disk[0-9]s[0-9]"
set b to do shell script "diskutil info " & a & " | awk '/Identifier/' | grep -o -e disk[[:digit:]]*"
set c to do shell script "diskutil info " & b & "| grep 'Media Name' | awk /'Name:/{print$5,$6}'"
choose from list c with prompt "Multiple EFI partitions found:"
display alert "Do you want to mount the EFI partition?" buttons {"Yes", "No"} default button 1
set response to button returned of the result
if response = "Yes" then
do shell script "diskutil mount " & a with administrator privileges
display alert result
end if
Note: when asked the user I want the disk name to be displayed and not something like: ''disk0s1''
Thanks in advance!
I wrote an EFI mount/unmount utility applet a while ago that uses an NSAlert with a combo box to try to avoid the death by dialog typical with AppleScripts. I extracted the script from that and added disk names to the initial dialog - the alert stuff makes it a bit longer than your snippet, but there should be something in there you can use:
use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
property alertHeader : " --- CAUTION ---" & return & "This utility works with EFI boot partitions -" & return & "Administrator authorization will be required."
property resources : "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/"
property leadText : " "
property identifiers : missing value -- this will be a list of the EFI partition identifiers, e.g. {disk0s1}
on run -- example can be run as app and from Script Editor
if current application's NSThread's isMainThread() as boolean then
doStuff()
else
my performSelectorOnMainThread:"doStuff" withObject:(missing value) waitUntilDone:true
end if
end run
on doStuff() -- the main stuff
set theDisks to setup() -- set up properties and get disks with EFI partitions, e.g. {/dev/disk0}
set reply to {button:missing value, answer:""} -- preset a previous empty dialog result
repeat -- forever
set theAnswer to answer of reply -- use previous
set reply to (showAlert given settings:{title:"EFI [un]Mounter", message:alertHeader, information:"EFI partitions have been found on the following disks:" & return & return & theDisks & return & "The EFI partition of the specified disk will be [un]mounted." & return & "Enter the disk identifier or select one from the menu:", answer:theAnswer, icon:(resources & "AlertCautionIcon.icns"), buttons:{"Cancel", "Mount", "Unmount", "More Info"}})
if button of reply is "Cancel" then error number -128
set diskID to checkID(answer of reply)
if diskID is not missing value then -- found it
if button of reply is "More Info" then
set reply to moreInfo(answer of reply) -- result of the moreInfo dialog
if button of reply is not "Change" then exit repeat
else
exit repeat
end if
else -- try again
beep
set answer of reply to ""
end if
end repeat
processEFI(button of reply, diskID)
end doStuff
to processEFI(command, diskID) -- mount or unmount the specified disk - admin authorization will be needed
log diskID
try
set command to (do shell script "echo " & command & " | tr [:upper:] [:lower:]")
if command is not in {"mount", "unmount"} then error "The processEFI handler received an invalid command."
set theResult to (do shell script "diskutil " & command & " /dev/" & diskID with administrator privileges)
if command is "mount" then tell application "Finder" -- show it
make new Finder window to ("/Volumes/EFI" as POSIX file)
activate
end tell
display notification theResult
delay 2
on error errmess
log errmess
showAlert given settings:{title:"EFI [un]Mounter", message:return & "There was an error processing the partition.", information:errmess, icon:(resources & "AlertCautionIcon.icns")}
end try
end processEFI
on moreInfo(diskID) -- get more information about the specified disk identifier
set infoText to ""
set diskName to (do shell script "diskutil info " & diskID & " | grep 'Media Name' | awk '{print substr($0,index($0,$5))}'")
if diskName is "" then
set diskName to "the following disk"
else
set diskName to "disk " & quoted form of diskName
end if
repeat with aParagraph in paragraphs of (do shell script "diskutil list " & diskID)
if aParagraph starts with leadText then -- trim information text
if (paragraph -2 of infoText does not start with leadText) then set infoText to infoText & leadText & trimWhitespace(text 1 thru -1 of contents of aParagraph) & return
else if aParagraph does not start with " #:" then -- don't include header text
if length of aParagraph is less than 56 then
set infoText to infoText & aParagraph & return
else -- trim description text
set infoText to infoText & space & space & space & text 1 thru 6 of aParagraph & tab & trimWhitespace(text 7 thru 56 of aParagraph)
set infoText to infoText & return
end if
end if
end repeat
set reply to (showAlert given settings:{title:"EFI [un]Mounter", message:alertHeader, information:"The EFI partition of " & diskName & " will be [un]mounted:" & return & return & infoText, icon:(resources & "AlertCautionIcon.icns"), buttons:{"Cancel", "Mount", "Unmount", "Change"}})
if button of reply is "Cancel" then error number -128
return {button:button of reply, answer:diskID}
end moreInfo
to showAlert given settings:arguments -- show a custom alert
set arguments to arguments & {title:"", message:"Alert", information:"", answer:missing value, icon:"", buttons:{"OK"}} -- a record is used for input parameters, unspecified keys will use default values
tell current application's NSAlert's alloc's init()
if (icon of arguments) as text is "Critical" then -- everything else is NSInformationalAlertStyle
set its alertStyle to current application's NSCriticalAlertStyle
else -- use the contents of an image file - informational icon will be used if no image or file (missing value)
set its icon to current application's NSImage's alloc's initByReferencingFile:((icon of arguments) as text)
end if
set its |window|'s title to (title of arguments) as text
set its messageText to (message of arguments) as text -- the bold text
set its informativeText to (information of arguments) as text -- the normal text
set buttonList to my (setButtons for it from (buttons of arguments))
if (answer of arguments) is not missing value then
set its |window|'s autorecalculatesKeyViewLoop to true
set accessory to my (makeComboAccessory for it)
set accessory's stringValue to answer of arguments
end if
activate me
set response to ((its runModal) as integer) - 999 -- get index - 1000 is rightmost button
end tell
if answer of arguments is not missing value then set answer of arguments to (accessory's stringValue) as text
return {button:item response of buttonList, answer:answer of arguments} -- returns a record: {button:(button title), answer:(text field value, or 'missing value' if not used)}
end showAlert
to setButtons for alert from buttons -- set buttons for the alert - filters for blanks and duplicates; returns a list of the button titles (left-to-right)
set {buttonList, theButton} to {{}, missing value}
repeat with aButton in reverse of (buttons as list) -- match dialog order
set aButton to aButton as text
if aButton is not in buttonList and aButton is not in {missing value, ""} then -- filter
set theButton to (alert's addButtonWithTitle:aButton)
set end of buttonList to aButton
end if
end repeat
if buttonList is {} then -- better have at least one
set theButton to alert's addButtonWithTitle:"OK"
set end of buttonList to "OK"
end if
set alert's |window|()'s initialFirstResponder to theButton -- the last (leftmost) one
return buttonList
end setButtons
to makeComboAccessory for alert -- make and return a comboBox accessory view for the alert
tell (current application's NSComboBox's alloc's initWithFrame:{{0, 0}, {288, 28}})
set its completes to true
set its hasVerticalScroller to true
set its placeholderString to "a disk identifier, for example disk0" -- arbitrary
repeat with anItem in identifiers -- populate the combo box with the disks with EFI partitions
set here to offset of "s" in (reverse of characters of anItem) as text
set anItem to text 1 thru -(here + 1) of anItem -- strip off partition
(its addItemWithObjectValue:anItem)
end repeat
set alert's accessoryView to it
return it
end tell
end makeComboAccessory
to checkID(diskID) -- check the disk identifier against the EFI partitions - returns the EFI partition, or missing value if not found
if diskID is not "" then repeat with anItem in identifiers
set anItem to anItem as text
set here to offset of "s" in (reverse of characters of anItem) as text -- partition index
if text 1 thru -(here + 1) of anItem is first word of diskID then return anItem
end repeat
return missing value
end checkID
to trimWhitespace(someText) -- trim whitespace characters from the beginning and end of a string
set someText to someText as text
if someText is "" then return ""
set whiteSpace to {space, tab, return, linefeed}
repeat until the first character of someText is not in whiteSpace
if (count someText) is 1 then return ""
set someText to text 2 thru -1 of someText
end repeat
repeat until the last character of someText is not in whiteSpace
if (count someText) is 1 then return ""
set someText to text 1 thru -2 of someText
end repeat
return someText
end trimWhitespace
to setup() -- set up properties and stuff
set {theDisks, identifiers} to {"", {}}
try
repeat with aPartition in paragraphs of (do shell script "diskutil list | grep 'EFI EFI' | grep -E -o 'disk[0-9]?[0-9]s[0-9]?[0-9]'") -- just EFI partitions named EFI
set aDisk to first paragraph of (do shell script "diskutil list " & aPartition)
if aDisk does not contain "disk image" then -- don't add disk images
set diskName to (do shell script "diskutil info " & text 1 thru -3 of aPartition & " | grep 'Media Name' | awk '{print substr($0,index($0,$5))}'")
if diskName is in {"", missing value} then
set diskName to ""
else
set diskName to "(" & diskName & ")"
end if
set theDisks to theDisks & tab & text 1 thru 11 of aDisk & space & diskName & return
set end of my identifiers to aPartition
end if
end repeat
if (count identifiers) < 1 then error "No EFI partitions were found."
return theDisks -- returns the disks found with EFI partitions (for the initial dialog)
on error errmess
log errmess
showAlert given settings:{title:"EFI [un]Mounter", message:return & errmess, icon:(resources & "AlertStopIcon.icns")}
error number -128
end try
end setup

How to save your desktop elements (icons, files,folder ) always on the same place with applescript

With the script we are going to create another script where will be store position of all the elements of the desktop, the created script will be compile and usable to put back in place all the elements previously protected.
/adesktopsave/deskico.txt it is the temporary file which will be of use to the compilation.
/adesktopsave/savedicoposition.scpt It is the script of saving that is compiled to be used with applescrit
All the names used here exist that just for the example. These names have no particular property.
It is just necessary to plan to create a folder before using this script. Here it is:
/adesktopsave
Something else, end of line (\n) after " try
"
also " end try
"
and & "}
")
Are very important to respect so that the text is usable.
tell application "Finder" to set theList to {name, desktop position} of items of desktop
try
do shell script "rm -f /adesktopsave/deskico.txt"
do shell script "echo tell application " & quoted form of (quote & "Finder" & quote) & return & " >>/adesktopsave/deskico.txt"
end try
set n to (count (first item of theList))
repeat with i from 1 to n
set inp to do shell script "echo " & quoted form of (item i of first item of theList)
set xy to (item i of second item of theList)
set AppleScript's text item delimiters to ","
set xyz to do shell script "echo " & xy
set wxyz to ("{" & xyz & "}
")
set ligne to "try
" & "set desktop position of item " & quoted form of (quote & inp & quote) & " of desktop to " & quoted form of (wxyz) & "end try
"
set ligne to do shell script "echo " & ligne & " >>/adesktopsave/deskico.txt"
end repeat
do shell script "echo " & "end tell" & return & " >>/adesktopsave/deskico.txt"
display dialog "Do you want to save your icons in their current location?" buttons {"Cancel", "Save"} default button 2 with title "Save the positions of icons"
if (button returned of result) is "Cancel" then
set n to do shell script "echo " & n
else
do shell script "osacompile -o " & "/adesktopsave/savedicoposition.scpt" & " /adesktopsave/deskico.txt"
end if
return n
We can lighten the script to its simplest expression. At the risk of having errors can be.
set ligne to ""
do shell script "mkdir -p /adesktopsave"
tell application "Finder" to set {names, positions} to {name, desktop position} of items of the desktop
set ligne to "tell application \"Finder\"
"
set n to (count names)
set AppleScript's text item delimiters to ","
repeat with i from 1 to n
set ligne to ligne & ("try
" & "set desktop position of item " & (quote & item i of names & quote) & " to {" & item i of positions & "}
end try
")
end repeat
set ligne to ligne & ("end tell" & return)
display dialog "Do you want to save your icons in their current location?" buttons {"Cancel", "Save"} default button 2 with title "Save the positions of icons"
if (button returned of result) is "Cancel" then
set n to do shell script "echo " & n
else
do shell script "osacompile -o " & "/adesktopsave/savedicoposition.scpt -e " & quoted form of ligne
end if
set AppleScript's text item delimiters to ""
tell application "Finder" to open POSIX file "/adesktopsave/savedicoposition.scpt"
return n

tell iTerm to open several ssh session

I've used some neat example's from attached URL's. What I've got so far is the script opening several tab's with ssh session's. But as I've several client's to whom's server's I connect I don't want a script with a hard coded list for every client. I want a dialod box asking to which list I'ld like to connect...
But now that I tried to add a dialog I'm stuck:
--set wseServer to {"xen", "bcs", "db", "lx", "mgr", "nx", "proxy", "smb", "wiki", "zarafa"} as list
set wseServer to paragraphs of (do shell script "/bin/cat $HOME/.ssh/hostlist-wse-deb.pssh")
--set edlServer to {"edl", "edev", "edb", "emon"}
set edlServer to paragraphs of (do shell script "/bin/cat $HOME/.ssh/hostlist-edl.pssh")
set allServer to wseServer & edlServer
set serverList to button returned of (display dialog "Dude, choose your prefered connection List" buttons {"wseServer", "edlServer", "allServer"} with title "SSH Server" default button 3 with icon caution giving up after 5)
tell application "iTerm"
activate
set myTerm to (make new terminal)
tell myTerm
repeat with hostItem in serverList
set Lsession to (make new session)
tell Lsession
--set secureshell to hostItem exec command "ssh " & hostItem
exec command "ssh " & hostItem
--sleep to prevent errors if we spawn too fast
do shell script "/bin/sleep 0.01"
end tell
end repeat
end tell
end tell
After choosing one of the items from the dialog iterm opens 8 Tabs, doesnt execute ssh and closes them... No error no nothing!
This is the example I'm trying to expand:
http://code.google.com/p/iterm2/wiki/AppleScript
I know I'm nearly there but can't see the solution!
Hope one of you has a hint...
Thx in advance
Answer to myself so it hopefully will help other's too:
removed all the stuff above the "tell application ..." and added this:
set sshList to {"WSE", "EDL", "Alle"}
set sshServer to choose from list sshList with title "SSH Server"
if sshServer = {"WSE"} then set serverList to paragraphs of (do shell script "/bin/cat $HOME/.ssh/hostlist-wse-deb.pssh")
if sshServer = {"EDL"} then set serverList to paragraphs of (do shell script "/bin/cat $HOME/.ssh/hostlist-edl.pssh")
if sshServer = {"Alle"} then set serverList to paragraphs of (do shell script "/bin/cat $HOME/.ssh/hostlist-wse-deb.pssh & /bin/cat $HOME/.ssh/hostlist-edl.pssh")
The dialog is not as beatyful as with the first attempt but it work's...
This could be useful: https://raw.github.com/luismartingil/scripts/master/iterm_launcher02.applescript
#!/usr/bin/osascript
-- Applescript to launch iterm2 terminals/tabs with configurable:
-- ~ List of commands <cmds>
-- ~ Color <color>
-- ~ Name <name>
-- ~ Transparency <trans>
-- ~ Zoom out <zoomout>
-- ~ Split behavior horizontal(h) or vertical(v) <split> :: (h, v)
--
-- Run from terminal with `osascript` or just ./<<script>>
-- Dont unfocus with the mouse/keyboard while executing. the script.
-- Recomended to go full screen (CMD + Enter) if <zoomout> attributes used.
-- Change myTermWindow and myItem(s) as desired.
--
--
-- Author: Luis Martin Gil http://www.luismartingil.com
-- Year : 2013
tell application "iTerm"
-- First tab
set myItem1 to {}
set myItem1 to myItem1 & {{color:"yellow", cmds:{"echo yellow", "ls -lrt"}, name:"name_yellow", trans:"0.1", zoomout:4, split:"h"}}
set myItem1 to myItem1 & {{color:"blue", cmds:{"echo blue1", "ls -lrt"}, name:"name_blue1", trans:"0.1", zoomout:2, split:"v"}}
set myItem1 to myItem1 & {{color:"blue", cmds:{"echo blue2", "ls -lrt"}, name:"name_blue2", trans:"0.1", zoomout:4, split:"v"}}
set myItem1 to myItem1 & {{color:"blue", cmds:{"echo blue3", "ls -lrt"}, name:"name_blue3", trans:"0.1", zoomout:6}}
-- Second tab
set myItem2 to {}
set myItem2 to myItem2 & {{color:"red", cmds:{"echo red1", "ls -lrt"}, name:"name_red1", trans:"0.1", zoomout:8, split:"h"}}
set myItem2 to myItem2 & {{color:"red", cmds:{"echo red2", "ls -lrt"}, name:"name_red2", trans:"0.1", zoomout:4}}
-- Third tab
set myItem3 to {}
set myItem3 to myItem3 & {{color:"green", cmds:{"echo green", "ls -lrt"}, name:"name_green", trans:"0.1", zoomout:2, split:"v"}}
set myItem3 to myItem3 & {{color:"purple", cmds:{"echo purple", "ls -lrt"}, name:"name_purple", trans:"0.1", zoomout:4}}
set myTermWindow to {myItem1, myItem2, myItem3}
set myterm to (make new terminal)
tell myterm
repeat with n from 1 to count of myTermWindow
launch session n
repeat with i from 1 to count of (item n of myTermWindow)
-- Lets set the properties of the actual tab
tell the last session to set name to name of (item i of (item n of myTermWindow))
tell the last session to set background color to color of (item i of (item n of myTermWindow))
tell the last session to set transparency to trans of (item i of (item n of myTermWindow))
-- Some commands might require more columns to be readable
repeat zoomout of (item i of (item n of myTermWindow)) times
tell i term application "System Events" to keystroke "-" using command down
end repeat
-- Lets execute the commands for the tab
repeat with cmd in cmds of (item i of (item n of myTermWindow))
tell the last session to write text cmd
end repeat
-- Split the pane in a "D" (vertical) or "d" (horizontal) way
if i is less than (count of (item n of myTermWindow)) then
if "h" is split of (item i of (item n of myTermWindow)) then
set split_str to "D"
else if "v" is split of (item i of (item n of myTermWindow)) then
set split_str to "d"
else
error
return
end if
tell i term application "System Events" to keystroke split_str using command down
end if
end repeat
end repeat
end tell
end tell

Resources