System-Preferences Applescript using osascript cannot select its window
So there are two ways this script can fail:


Command line version unable to get the System Preferences window.
Running it will cause the complaint about enabling access for assistive devices.


Well the latter case as it turns out is self-explanatory: This script requires that you have enabled access for assistive devices.  The former is still not obvious, but if you quit System Preferences and restart it then it might work; it finally did for me, and I have amended the code above to get System Preferences to quit at the end.