Reputation: 726
I use the following script to rotate my portable monitor automatically.
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "ASUS MB16AC"
click radio button "Display" of tab group 1
click pop up button "Rotation:" of tab group 1
click menu item "90°" of menu 1 of pop up button "Rotation:" of tab group 1
set success to 0
repeat until success is equal to 1
delay 1
try
tell sheet 1
click button "Confirm"
set success to 1
end tell
on error errText
log errText
delay 1
end try
end repeat
end tell
quit application "System Preferences"
When calling the script with osascript
on Terminal, I get the following error message, but the code does the job anyway.
System Events got an error: Can’t get sheet 1 of window "ASUS MB16AC" of process "System Preferences". Invalid index.
How can this error be avoided?
-----
The script worked without error when run under the Script Editor
.
The error only came up when I execute the script from Terminal using osascript
.
Upvotes: 1
Views: 195
Reputation: 7555
The following example AppleScript code is how I would code it, and this works for me, as is, in macOS High Sierra:
if running of application "System Preferences" then
try
tell application "System Preferences" to quit
on error
do shell script "killall 'System Preferences'"
end try
end if
repeat while running of application "System Preferences" is true
delay 0.1
end repeat
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window 1
click pop up button 1 of tab group 1
click menu item 2 of menu 1 of pop up button 1 of tab group 1
repeat until exists sheet 1
delay 0.5
end repeat
click button 1 of sheet 1
delay 0.1
end tell
tell application "System Preferences" to quit
Note: The example AppleScript code is just that and sans included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.
Upvotes: 1
Reputation: 3184
Check to see if the sheet exists before trying to click the button, like so:
repeat until success is equal to 1
delay 1
if exists sheet 1 then
try
tell sheet 1
click button "Confirm"
set success to 1
end tell
on error errText
log errText
delay 1
end try
end if
end repeat
With that if exists
block you probably won't even need the try block.
Upvotes: 1