How to I use Apple Script to change the keyboard layout on Snow Leopard? [duplicate]

The current keyboard layout appears to be saved in ~/Library/Preferences/ByHost/com.apple.HIToolbox.machineid.plist under the key AppleCurrentKeyboardLayoutInputSourceID. Your ID is a 12-digit hexadecimal number. Inspect the ByHost folder to see what I mean.

You can write preferences to this file using the defaults command in Terminal. For example, the following commands change this preference to the US keyboard then restart SystemUIServer, the process that handles the Input Source menu.

defaults write ~/Library/Preferences/ByHost/com.apple.HIToolbox.0017f2c31710 AppleCurrentKeyboardLayoutInputSourceID -string "com.apple.keylayout.US"
killall SystemUIServer

However, this seems to change the keyboard only about 80% of the time.

You can run Terminal commands from AppleScript easily using do shell script.