System-Preferences Applescript using osascript cannot select its window

This AppleScript (based on an answer in a MacWorld form) will tell me whether or not Screen Sharing is enabled:

tell application "System Preferences"
    reveal pane "com.apple.preferences.sharing"
end tell

tell application "System Events"
    tell process "System Preferences"
        set screen_sharing_toggle to value of (checkbox 1 of row 2 of table 1 of scroll area 1 of group 1 of window 1) as boolean
    end tell
end tell

tell application "System Preferences"
        Quit
end tell

set newvar to screen_sharing_toggle

So if I run that in the AppleScript editor it returns true or false depending on the setting of Screen Sharing. If I try running it on the command line (which is what I really want) I get something like this:

scriptname: execution error: System Events got an error: Can’t get window 1 of process "System Preferences". Invalid index. (-1719)

Some more information

If I use run a script like this to count System Preferences' windows:

tell application "System Preferences"
    reveal pane "com.apple.preferences.sharing"
end tell

tell application "System Events"
    tell process "System Preferences"
        count windows
    end tell
end tell

it returns 1 when running under AppleScript editor, but 0 when I run it using osascript.

Even more information: On my laptop I get an even stranger error running the same command:

execution error: System Events got an error: Access for assistive devices is disabled. (-1719)

Solution 1:

So there are two ways this script can fail:

  1. Command line version unable to get the System Preferences window.
  2. 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.