The example AppleScript code, shown below, was tested in Script Editor under macOS Monterey 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.
Example AppleScript code:
my changeKeyboardLayoutTo("U.S.")
to changeKeyboardLayoutTo(layoutName)
ignoring application responses
tell application "System Events" to ¬
click menu bar item 1 of menu bar 2 of ¬
application process "TextInputMenuAgent"
end ignoring
delay 0.1
do shell script "killall 'System Events'"
delay 0.2
tell application "System Events"
launch
click menu item layoutName of menu 1 of ¬
menu bar item 1 of menu bar 2 of ¬
application process "TextInputMenuAgent"
end tell
end changeKeyboardLayoutTo
Notes:
The example AppleScript code assumes one has checked Show Input menu in menu bar in: System Preferences > Keyboard Input Sources
The example AppleScript code is also coded to workaround the ~5 second delay that is a know issue between actuating the primary menu and the the target menu item on the menu.
See my answer A: AppleScript - Can't get rid of delay after click for the reference to mentioned ~5 second delay, which still persists in macOS Big Sur and macOS Monterey. It also includes other methods to click the target menu items that can be adapted as/if needed. Although I have not tested the alternate solutions in macOS Monterey yet.
Note: The example AppleScript code is just that and sans any 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. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.