MacOS – Using AppleScript to toggle Internet Sharing not working

applescriptinternet-sharingmacossystem-prefs

I am using an applescript to activate internet sharing option from 'System Pref> Sharing'. I work on MacOs 10.9.4. I found this script on a forum and am using it. This works fine, when the System Preferences window is open. However,when the System Preferences window is closed, the script opens the System Prefs window and then displays this error message:

 System Events got an error: Can’t get menu item \"Sharing\" of menu \"View\" of menu bar 1 of process \"System Preferences\"." number -1728 from menu item "Sharing" of menu "View" of menu bar 1 of process "System Preferences"

This is the code for the script

tell application "System Preferences"
        activate
    end tell
    tell application "System Events"
        activate
        tell process "System Preferences"

            click menu item "Sharing" of menu "View" of menu bar 1
            delay 2
            tell window "Sharing"...
//code after this 

I am not proficient in AppleScript ,but only need to use this one to get a keyboard shortcut for toggling internet sharing. Also, the forum I got it from says the other users are able to use the script. I wonder if it has something to do with MAcOs 10.9

Best Answer

You can use this code to activate sharing with settings which were already there:

tell application "System Preferences"
    activate
    set current pane to pane "com.apple.preferences.sharing"
end tell
tell application "System Events" to tell process "System Preferences"

    --find lock and click it if it is not unlocked
    repeat with x in buttons of window "Sharing"
        try
            if (value of attribute "AXTitle" of x) is equal to "Click the lock to make changes." then
                click x
            end if
        end try
    end repeat
    delay 5

    --find the checkbox for Internet Sharing and select the row so script can enable sharing through ethernet
    repeat with r in rows of table 1 of scroll area 1 of group 1 of window "Sharing"
        if (value of static text of r as text) starts with "Internet" then
            select r
        end if
    end repeat
    delay 2

    --enable Internet Sharing
    repeat with r in rows of table 1 of scroll area 1 of group 1 of window "Sharing"
        if (value of static text of r as text) starts with "Internet" then
            set sharingBool to value of checkbox of r as boolean
            select r
            if sharingBool is false then click checkbox of r
        end if
    end repeat
    delay 2

    if (exists sheet 1 of window "Sharing") then
        click button "Start" of sheet 1 of window "Sharing"
    end if
    delay 2

end tell
ignoring application responses
    tell application "System Preferences" to quit
end ignoring

Hope this helps!