AppleScript to automate switching user not working in Monterey
I have the following AppleScript that's supposed to automatically switch to the Administrator user. It worked in Big Sur, but isn't working in Monterey.
tell application "System Events"
tell its application process "ControlCenter"
tell its menu bar 1
click its menu bar item "barmar"
end tell
tell its window "Control Center"
tell its group 1
set btns to its buttons
repeat with btn in btns
if name of btn = "Administrator" then
click btn
end if
end repeat
end tell
end tell
end tell
end tell
It gets the following error:
System Events got an error: Can’t get group 1 of window "Control Center" of application process "ControlCenter". Invalid index."
number -1719 from group 1 of window "Control Center" of application process "ControlCenter"
The list of users is popping up, but it's failing on "tell its group 1".
Assuming you are targeting the Fast User Switching menu bar item, then you do not need tell its group 1
as there is no group 1
.
Also, you are using far more code than necessary, as the following works for me:
Example AppleScript code:
tell application "System Events"
tell application process "Control Center"
click (first menu bar item of menu bar 1 ¬
whose value of attribute "AXIdentifier" is "com.apple.menuextra.user")
click (first button of window "Control Center" whose name is "Administrator")
end tell
end tell
Notes:
As coded, it does not matter how Show fast user switching menu as is set under System Preferences > Users & Groups > Login Options for the Fast User Switching menu bar item. It work with Icon, Account Name, or Full Name as it uses a different criteria to click the Fast User Switching menu bar item.
The example AppleScript code, shown above, was tested in Script Editor under macOS Monterey 12.0.1 with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
- 1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
attribute "AXIdentifier" "com.apple.menuextra.user"
exists in macOS Big Sur and macOS Monterey.