AppleScript – Fix Invalid Index Error in Control Center

applescript

tell application "System Events"
    tell its application process "ControlCenter"
        tell its menu bar 1
            click its menu bar item "User"
        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 = "BrilliantCorners" then
                        click btn
                    end if
                end repeat
            end tell
        end tell
        
        delay 1
        set thePassword to "mypassword" -- Mac user password
        tell application "System Events"
            tell process "SecurityAgent"
                set value of text field 1 of window "Login" to thePassword
                key code 36
            end tell
        end tell
        
    end tell
end tell

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"

This script worked just fine before I upgraded to Monterey, now it's getting stuck for some reason I can't figure out. Any ideas?

Best Answer

In macOS Monterey, using the AppleScript code in your question, I was able to get it to work by removing the tell its group 1 statement and its closing end tell statement, e.g.:

tell application "System Events"
    tell its application process "ControlCenter"
        tell its menu bar 1
            click its menu bar item "User"
        end tell
        
        tell its window "Control Center"
                set btns to its buttons
                repeat with btn in btns
                    if name of btn = "BrilliantCorners" then
                        click btn
                    end if
                end repeat
        end tell 

Notes:

The AppleScript code shown herein is just a snippet of your original code and does not show the remaining working code as tested.