Problem

Hi All,

I write a script (applet) to turn on wi-fi, using UI Browser and have Calender run it at 5 am. When run by Calendar, an error occurs (see below). The script is opened in Script Editor and the line click button “Turn Wi-Fi On” of group 1 of window “Network” is highlighted as the problem.
However, if I run it via Apple Script Editor or Script Debuggger, it runs fine without any problems.

(This is the error message)
Can’t get <> “Turn Wi-Fi On” of <> 1 of window “Network” of <> “System Preferences” of application “System Events”.

System Events got an error: Can’t get button “Turn Wi-Fi On” of group 1 of window “Network” of process “System Preferences” . (-1728)

(This is the code)
tell application “System Preferences”
activate
tell application “System Events”
activate
tell process “System Preferences”
set frontmost to true
click menu item “Show All Preferences” of menu 1 of menu bar item “View” of menu bar 1 — Show all Prefs
delay 1
click button “Network” of scroll area 1 of window “System Preferences” — Select NETWORK Prefs
delay 1
select row 6 of table 1 of scroll area 1 of window “Network” — Select Wi-Fi
delay 1
click button “Turn Wi-Fi On” of group 1 of window “Network” — Turn Off Wi-Fi
delay 1
click menu item “Show All Preferences” of menu 1 of menu bar item “View” of menu bar 1 — Show all Prefs
click menu item “Energy Saver” of menu 1 of menu bar item “View” of menu bar 1 — Select ENERGY SAVER Prefs
click button “Restore Defaults” of group 1 of window “Energy Saver” — Select default settings
—click checkbox “Put hard disks to sleep when possible” of group 1 of window “Energy Saver” — Turn ON & OFF checkbox.
end tell
end tell
end tell

What am I doing wrong?

Help.

Willis

Model: MiniMac
AppleScript: 2.4
Browser: Chrome 78.0
Operating System: macOS 10.10

Hi, willisbar

Your script fails because when you toggle Wi-Fi state between On and Off the toggle’s position as you see it on the screen and the corresponding index in GUI hierarchy changes too, and as a consequence, its row can neither be 6th nor 1st at any given moment.
Also you can do without selecting rows from the scroll area on the left because a single and the only group to which the toggle switch belongs is contained by the window which is single and the only window as well. It means that the button to turn on/and off sits persistently regardless of your selection in the right scroll area so we can omit that part and come up with:

tell application "System Events"
	tell application process "System Preferences"
		tell window 1
			tell group 1
				tell first item of (every UI element whose role is "AXButton" and title contains "Wi-Fi")
					perform action "AXPress"
				end tell
			end tell
		end tell
	end tell
end tell

Insert this snippet in the appropriate place of your code.
Also, you’ll probably notice that I used the form of GUI elements and commands as it appears in Accessibility Inspector which is part of Xcode because I find it more reliable. The only keys from System Events dictionary used in this case were “role” property and the classes of elements that are obvious from the get-go.

Model: MacBook Pro
AppleScript: 2.3.2
Browser: Safari 9537.86.7
Operating System: macOS 10.9

Hi scrutinizer82,

Thanks for your response.
I am not familiar with Xcode, or with “AXPress” or “AXButton” in UI Browser, so I am lost where those 2 are concern. I am not a programmer, I found Applescript easy to follow and learn and I am able to write small scripts to help myself.

(An explanation for using row 6 of table 1 of scroll area 1 of window "Network)

In the left panel of the Network window, there are 7 connections options to choose from, eg, SAMSUNG Modem, SAMSUNG Serial, Ethernet, Fire-Wire, Bluetooth DUN, WI-FI, Bluetooth PAN.

WI-FI always sits in 6th position, so I use "select row 6 of table 1 of scroll area 1 of window “Network” to select. Also “Turn Wi-Fi On” will only appears when I select the WI-FI option, so I must select WI-FI by all means to get to “Turn Wi-Fi On”.

I tried to implement your suggestion in my code without any success, so maybe you can insert it my code for me.

Thanks again
Willis

Model: MiniMac
AppleScript: 2.4
Browser: Chrome 78.0
Operating System: macOS 10.10

As I mentioned earlier a position of the row corresponding to the Wi-Fi section of the Network preferences window is volatile depending on its status. At least this is the behaviour in Mavericks however I’m sure it’s valid for as recent macOS as High Sierra. When you turn it off it moves down and gets back to the top if activated again: this is, of course, taking into consideration the situation when other connection schemes are inactive. If they are active then the fixed position you supply to the script will result in errors.
Therefore there should be a way to identify “Wi-Fi” connection setting. The code I posted earlier allows for such a possibility. The final draft of the code will look as follows:

tell application "System Events"
	tell application process "System Preferences"
		tell window 1
			tell scroll area 1
				tell table 1
					repeat with aRow in every row
						if title of contents of aRow contains "Wi-Fi" then
							select (contents of aRow)
							exit repeat
						end if
					end repeat
				end tell
			end tell
			delay 0.3
			tell group 1
				tell first item of (every UI element whose role is "AXButton" and title contains "Wi-Fi")
					perform action "AXPress"
				end tell
			end tell
		end tell
	end tell
end tell
 

After targeting the table you then loop through its rows to find the one that pertains to the “Wi-Fi” setting.
Since I don’t use UIbrowser I’m content with a free tool that’s available as part of Xcode and it doesn’t require you to possess sophisticated programming skills.

Wi-Fi power management is important. I think you’d better to use non-GUI scripting way.

–Turn on/off Wi-Fi power
http://piyocast.com/as/archives/5709

maro has a point. However one should be able to leverage “Network Preferences” suite of “System Events” which would let to get by without GUI scripting. A code as simple as

tell application "System Events"
	set MyServices to every service of current location of network preferences
	repeat with i from 1 to number of items in MyServices
		set this_item to item i of MyServices
		if name of contents of this_item contains "Wi-Fi" then
			disconnect (contents of this_item) -- or "connect" if WiFi is off
			exit repeat
		end if
	end repeat
end tell

should work but for some reason it doesn’t. No matter if I connect or disconnect Wi-Fi its active property is always true and its set of configurations is always missing value.

For this reason my code above should replace the entire segment of the OP’s code beginning with [format]select row 6 of table 1 of scroll area 1 of window “Network”[/format]
and ending with
[format]click button “Turn Wi-Fi On” of group 1 of window “Network”[/format]

Model: MacBook Pro
AppleScript: 2.3.2
Browser: Safari 9537.86.7
Operating System: macOS 10.9

As I am a pig headed guy, at last I found how to grab the localized strings so I edited my original script.

set theRoot to (path to library folder from system domain as text) & "PreferencePanes:"
set theBundle to theRoot & "EnergySaver.prefPane:"
set EnergySaver_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Économiseur d’énergie"
set theBundle to theRoot & "Network.prefPane:"
set network_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Réseau"
set TURN_AIRPORT_ON_loc to localized string "TURN_AIRPORT_ON" from table "Localizable" in bundle file theBundle --> "Activer le Wi-Fi"

tell application "System Preferences" to activate
delay 1
tell application id "com.apple.systemevents" to tell process "System Preferences"
	set frontmost to true
	tell menu bar 1
		--get name of menu bar items --> {"Apple", "Préférences Système", "Édition", "Présentation", "Fenêtre", "Aide"}
		--get name of menu bar item 4 --> "Présentation"
		tell menu bar item 4 to tell menu 1
			--get name of menu items --> {"Précédent", "Suivant", "Afficher toutes les préférences", "Personnaliser…", missing value, "Classer par catégorie", "Classer par ordre alphabétique", "Rechercher", missing value, "Accessibilité", "App Store", "Bluetooth", "Bureau et économiseur d’écran", "CD et DVD", "Clavier", "Comptes Internet", "Contrôle parental", "Date et heure", "Démarrage", "Dock", "Économiseur d’énergie", "Extensions", "Flash Player", "Général", "iCloud", "Imprimantes et scanners", "Java", "Langue et région", "Mission Control", "Moniteurs", "Notifications", "Partage", "Réseau", "Sécurité et confidentialité", "Siri", "Son", "Souris", "Spotlight", "Time Machine", "Trackpad", "Utilisateurs et groupes", "Activer le mode plein écran"}
			click menu item EnergySaver_loc
		end tell
	end tell
	delay 1
	tell window 1
		--class of UI elements --> {button, button, group, button, button, button, toolbar}
		tell group 1
			--class of UI elements --> {list, list, button, checkbox, static text, static text, static text, static text, static text, static text, static text, slider, static text, static text, static text, static text, static text, static text, static text, slider}
			--name of button 1 --> "Rétablir les réglages par défaut"
			click button 1
		end tell
	end tell
	
	# Now switch to the pane Network
	tell menu bar 1
		tell menu bar item 4 to tell menu 1
			click menu item network_loc
		end tell
	end tell
	delay 1
	# Here the pane "Network" is active
	tell window 1
		--class of UI elements --> {static text, pop up button, scroll area, button, button, menu button, group, button, button, button, button, button, button, button, toolbar}
		tell scroll area 1
			--class of UI elements --> {table}
			tell table 1
				--class of UI elements --> {row, row, row, row, row, row, column}
				repeat with aRow in rows
					if (name of static text 1 of aRow) contains "Wi-Fi" then
						select aRow
						exit repeat
					end if
				end repeat
			end tell # table 1
		end tell # scroll area 1
		tell group 1
			--class of UI elements --> {static text, static text, group, button, static text, pop up button, checkbox, checkbox, static text, checkbox}
			tell button 1
				--set itsName to its name --> "Activer le Wi-Fi"
				if its name is TURN_AIRPORT_ON_loc then click it
			end tell
		end tell
	end tell
end tell

As you may see, several instructions are disabled.
They were used to grab the required informations about UI elements.
Disabling them force me to change the delays from .5 to 1.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) vendredi 6 décembre 2019 19:06:50

Hi Yvan Koenig,

Woooow, this works.

Hey maro,
Your suggestion works as well

Thanks a mil to all who has offered helped with my promise and share their knowledge
with me.

Many thanks again
Cheers
Willisbar

Model: MiniMac
AppleScript: 2.4
Browser: Chrome 78.0
Operating System: macOS 10.10

I tried to use the structure of the original code and built:

# Grab localized strings
set theRoot to (path to library folder from system domain as text) & "PreferencePanes:"
set theBundle to theRoot & "EnergySaver.prefPane:"
set EnergySaver_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Économiseur d’énergie"
set NSPrefPaneIconLabel_loc to localized string "NSPrefPaneIconLabel" from table "InfoPlist" in bundle file theBundle (*"Économiseur
d’énergie"*)
set theBundle to theRoot & "Network.prefPane:"
set network_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Réseau"
set TURN_AIRPORT_ON_loc to localized string "TURN_AIRPORT_ON" from table "Localizable" in bundle file theBundle --> "Activer le Wi-Fi"

set theBundle to path to application "System Preferences"

tell application "System Preferences"
	activate
end tell

set shortDelay to 0.1 # May need a greater value on some machines

tell application "System Events"
	activate
	set SystemPreferences_loc to localized string "System Preferences" in bundle theBundle --> "Préférences Système"
	tell process "System Preferences"
		set frontmost to true
		# Use keyboard shortcut to show all prefs. No need for a localized string
		keystroke "l" using {command down}
		# Wait for window System Preferences
		repeat until name of window 1 is SystemPreferences_loc
			delay 0.1
		end repeat
		# Switch to the pane Network
		click button network_loc of scroll area 1 of window 1
		# Wait for window Network
		repeat until name of window 1 is network_loc
			delay 0.1
		end repeat
		select (first row of table 1 of scroll area 1 of window network_loc whose name of static text 1 contains "Wi-Fi") --- Select Wi-Fi
		delay shortDelay
		tell button 1 of group 1 of window network_loc
			if its name is TURN_AIRPORT_ON_loc then click it --- Turn Off Wi-Fi
		end tell
		delay shortDelay
		# Use keyboard shortcut to show all prefs. No need for a localized string
		keystroke "l" using {command down}
		# Wait for window System Preferences
		repeat until name of window 1 is SystemPreferences_loc
			delay 0.1
		end repeat
		# Switch to the pane Energy Saver
		click button NSPrefPaneIconLabel_loc of scroll area 1 of window 1
		# Wait for window Energy Saver
		repeat until name of window 1 is EnergySaver_loc
			delay 0.1
		end repeat
		tell group 1 of window EnergySaver_loc
			--name of button 1--> "Rétablir les réglages par défaut"
			click button 1 --- Select default settings
			--title of checkbox 1 --> "Suspendre dès que possible l’activité des disques durs"
			# Click the checkbox if it isn't
			if value of checkbox 1 is 0 then click checkbox 1
		end tell
	end tell
end tell

For info, I warned DevonThink - authors of EasyFind - that their app is unable to find the string “Réseau” (as well as the string “seau”) available in the package Network.prefPane.
Same oddity with “Économiseur d’énergie” available in the package EnergySaver.prefPane.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) samedi 7 décembre 2019 14:30:18

Edited so that we wait the needed delay when switching windows

The script indicated above by maro and written by Shane Stanley and maro is the best aproach to set WiFi on/off.

To set WiFi on/off with GUI scripting you can use the following script with automated delay setting. The correct delay here is important. Your main mistake is that you request for button “Turn Wi-Fi On” when WiFi is ON… And when WiFi is ON, in the System Preferences in the given case present is button “Turn Wi-Fi Off” and vice versa. Other mistake is that you should tell to tab group 1 of window “Energy Saver” instead of group 1:

So, your entire script should be like this (assuming that WiFi is currently ON):


tell application "System Preferences"
	activate
	reveal anchor "Wi-Fi" of pane id "com.apple.preference.network"
	repeat until window "Network" exists
		delay 0.1
	end repeat
end tell

tell application "System Events" to tell process "System Preferences"
	tell window "Network" to tell group 1 to click button 1
	click menu item "Energy Saver" of menu 1 of menu bar item "View" of menu bar 1
	repeat until window "Energy Saver" exists
		delay 0.1
	end repeat
	click button "Restore Defaults" of tab group 1 of window "Energy Saver"
	click checkbox "Put hard disks to sleep when possible" of tab group 1 of window "Energy Saver"
end tell

tell application "System Preferences" to quit

Hi KniazidisR,

Your solution works as well, however “tab group 1” does not work on my system, only “group 1”
Maybe it’s because I am using OSX 10.10.5

Thanks again for your help,
Cheers,
Willisbar

Model: MiniMac
AppleScript: 2.4
Browser: Chrome 78.0
Operating System: macOS 10.10

Hello Hi KniazidisR.
To get your script to work I was forced to make more changes than those required by localization.

# Grab localized strings
set theRoot to (path to library folder from system domain as text) & "PreferencePanes:"
set theBundle to theRoot & "EnergySaver.prefPane:"
set EnergySaver_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Économiseur d’énergie"
set NSPrefPaneIconLabel_loc to localized string "NSPrefPaneIconLabel" from table "InfoPlist" in bundle file theBundle (*"Économiseur
d’énergie"*)
set sleep_loc to localized string "sleep" from table "Localizable" in bundle file theBundle --> "Suspendre"

set theBundle to theRoot & "Network.prefPane:"
set network_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Réseau"
set TURN_AIRPORT_ON_loc to localized string "TURN_AIRPORT_ON" from table "Localizable" in bundle file theBundle --> "Activer le Wi-Fi"

tell application "System Preferences"
	activate # REQUIRED under my Operating System
	reveal anchor "Wi-Fi" of pane id "com.apple.preference.network"
	repeat until window network_loc exists
		delay 0.1
	end repeat
end tell

tell application "System Events" to tell process "System Preferences"
	# Switch to the pane Network # REQUIRED under my Operating System
	select (first row of table 1 of scroll area 1 of window network_loc whose name of static text 1 contains "Wi-Fi") --- Select Wi-Fi
	tell window network_loc to tell group 1 to tell button 1
		if its name is TURN_AIRPORT_ON_loc then click it
	end tell
	click menu item EnergySaver_loc of menu 1 of menu bar item 4 of menu bar 1
	repeat until window EnergySaver_loc exists
		delay 0.1
	end repeat
	tell window EnergySaver_loc
		set theClasses to class of UI elements --> {button, button, group, button, button, button, toolbar}
		if theClasses doesn't contain group then # EDITED
			# Must be the case with 10.15, don't know for 10.14
			tell tab group 1
				click button 1
				set theCheckbox to first checkbox whose name contains sleep_loc
			end tell
		else
			# For systems older that 10.14 (maybe for 10.14 too)
			tell group 1
				click button 1
				-- set theCheckbox to first checkbox whose name contains sleep_loc
				# Under 10.13.6, there is a single checkbox in the group
				set theCheckbox to checkbox 1
			end tell
		end if
		if value of theCheckbox = 0 then click theCheckbox
	end tell
end tell

May you check if it’s OK for 10.15 and 10.14 which I can’t install ?

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 8 décembre 2019 14:40:03

I edited a test because under Catalina, the checked UI object isn’t reported as tab group but as tab and checking for tab fails. So I replaced the original
if theClasses contains tab group then
by
if theClasses doesn’t contain group then # EDITED

Your code runs fine until code line click button 1. It throws AppleScript execution error "“System Events got an error: Can’t get group 1 of window “Energy Saver” of process “System Preferences”. Invalid index.”

It is because you should use try…on error… block instead of if…then… block.

The classes on my machine returns {button, button, button, button, checkbox, image, tab, button, button, button, toolbar}

Here theClasses is {button, button, group, button, button, button, toolbar}

so I try to reach the UI items in group 1 which are : → {list, list, button, checkbox, static text, static text, static text, static text, static text, static text, static text, slider, static text, static text, static text, static text, static text, static text, static text, slider}

In your script you use:

click button “Restore Defaults” of tab group 1 of window “Energy Saver”
click checkbox “Put hard disks to sleep when possible” of tab group 1 of window “Energy Saver”

So I assumed that on your system there is an ui element whose class is tab group. It seems that I was wrong.
Is it in fact the UI element whose class is “tab” which contain the two targeted objects ?

For sure, I may code :

tell window EnergySaver_loc
	try
		# Must be the case with 10.15, don't know for 10.14
		tell tab group 1
			click button 1
			set theCheckbox to first checkbox whose name contains sleep_loc
		end tell
	on error
		# For systems older that 10.14 (maybe for 10.14 too)
		tell group 1
			class of UI elements
			click button 1
			-- set theCheckbox to first checkbox whose name contains sleep_loc
			# Under 10.13.6, there is a single checkbox in the group
			set theCheckbox to checkbox 1
		end tell
	end try
	if value of theCheckbox = 0 then click theCheckbox
end tell

but I continue to think that it’s more logical to identify the kind of objects available and behave accordingly.

I met some cases were Apple used three different UI hierarchy. Identifying the available one is cleaner than trying to execute upon these different structures.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 8 décembre 2019 17:11:16

As I wrote above, Easyfind is unable to find a string like “Réseau” in the Resources files of preferencePanes.
I decided to write my own search tool. Here is what I got:

----------------------------------------------------------------
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
----------------------------------------------------------------

on searchIn:targetDir forKey:theKey
	set theFolderURL to current application's NSURL's fileURLWithPath:(POSIX path of targetDir)
	set NSFileManager to a reference to current application's NSFileManager's defaultManager()
	set theOptions to (current application's NSDirectoryEnumerationSkipsHiddenFiles as integer)
	set theURLs to (NSFileManager's enumeratorAtURL:theFolderURL includingPropertiesForKeys:{} options:theOptions errorHandler:(missing value))'s allObjects()
	if theURLs is equal to missing value then error (theError's localizedDescription() as text)
	
	repeat with aURL in theURLs
		set aName to (aURL's lastPathComponent()) as text
		if aName is in {"Fr.lproj", "French.lproj"} then
			set someURLs to (NSFileManager's enumeratorAtURL:aURL includingPropertiesForKeys:{} options:theOptions errorHandler:(missing value))'s allObjects()
			if someURLs is not equal to missing value then
				repeat with anURL in someURLs
					if anURL's pathExtension() as text is "strings" then
						set theDict to (current application's NSDictionary's dictionaryWithContentsOfURL:anURL)
						set enListe to (item 1 of (theDict as list)) as list
						considering case
							if enListe contains theKey then
								tell application "BBEdit" to open ((anURL as text) as alias)
							end if
						end considering
					end if
				end repeat
			end if
		end if
	end repeat
end searchIn:forKey:

#=====

set targetDir to (path to library folder from system domain as text) & "PreferencePanes:"
--set targetDir to (path to desktop as text) & "scan:"
--my searchIn:targetDir forKey:"Activer le Wi-Fi"
my searchIn:targetDir forKey:"Réseau"

Is it a better way to do the job ?

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 8 décembre 2019 17:20:04

I found 1 flaw in my code. System Preferences requires a password to set Energy Saver to its default values. Still assuming that WiFi is connected, the code should be like this:


tell application "System Preferences"
	activate
	reveal anchor "Wi-Fi" of pane id "com.apple.preference.network"
	repeat until window "Network" exists
		delay 0.1
	end repeat
end tell

tell application "System Events" to tell process "System Preferences"
	tell window "Network"
		tell scroll area 1 to tell table 1 to select (first row whose (name of static text 1) contains "Wi-Fi")
		tell group 1 to click button 1
	end tell
	click menu item "Energy Saver" of menu 1 of menu bar item "View" of menu bar 1
	repeat until window "Energy Saver" exists
		delay 0.1
	end repeat
	tell window "Energy Saver"
		click UI element "Click the lock to make changes."
		repeat while text field "Enter password" of sheet 1 exists
			delay 0.1
		end repeat
		click radio button "Battery" of tab group 1
		click button "Restore Defaults" of tab group 1
		click radio button "Power Adapter" of tab group 1
		click button "Restore Defaults" of tab group 1
	end tell
end tell

tell application "System Preferences" to quit

Again I was forced to make changes to get a script working correctly under 10.13.6

# Grab localized strings
set theRoot to (path to library folder from system domain as text) & "PreferencePanes:"
set theBundle to theRoot & "EnergySaver.prefPane:"
set EnergySaver_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Économiseur d’énergie"
set NSPrefPaneIconLabel_loc to localized string "NSPrefPaneIconLabel" from table "InfoPlist" in bundle file theBundle (*"Économiseur
d’énergie"*)
set battery_loc to localized string "Battery Power" from table "Localizable" in bundle file theBundle --> "la batterie"
set powerAdapter_loc to localized string "AC Power" from table "Localizable" in bundle file theBundle --> "l’adaptateur secteur"
set restoreDefaults_loc to localized string "Restore Defaults" from table "Keyboard" in bundle file theBundle --> "Rétablir les réglages par défaut"
set sleep_loc to localized string "sleep" from table "Localizable" in bundle file theBundle --> "Suspendre"

set theBundle to theRoot & "Network.prefPane:"
set network_loc to localized string "CFBundleName" from table "InfoPlist" in bundle file theBundle --> "Réseau"
set TURN_AIRPORT_ON_loc to localized string "TURN_AIRPORT_ON" from table "Localizable" in bundle file theBundle --> "Activer le Wi-Fi"

set theBundle to (path to library folder from system domain as text) & "CoreServices:SecurityAgentPlugins:loginwindow.bundle:"
set enterPassword_loc to localized string "PASSWORD" from table "loginwindow" in bundle file theBundle --> "Pour modifier, cliquez sur le cadenas."

set theBundle to (path to library folder from system domain as text) & "Frameworks:SecurityInterface.framework"
set clickTheLock_loc to localized string "Click the lock to make changes." from table "Localizable" in bundle file theBundle --> "Pour modifier, cliquez sur le cadenas."

tell application "System Preferences"
	activate
	# CAUTION, doesn't select the Wi-Fi if Wi-Fi is not active, just reveal the pane Network
	reveal anchor "Wi-Fi" of pane id "com.apple.preference.network"
	
	repeat until window network_loc exists
		delay 0.1
	end repeat
end tell

tell application "System Events" to tell process "System Preferences"
	tell window network_loc
		# Required if WI-Fi is not active on entry
		tell scroll area 1 to tell table 1
			select (first row whose (name of static text 1) contains "Wi-Fi")
		end tell
		tell group 1 to tell button 1
			if its name is TURN_AIRPORT_ON_loc then click it
		end tell
	end tell
	
	click menu item EnergySaver_loc of menu 1 of menu bar item 4 of menu bar 1 # 4 is not localization dependant
	
	repeat until window EnergySaver_loc exists
		delay 0.1
	end repeat
	tell window EnergySaver_loc
		if (class of UI elements) contains group then
			tell button 1 of group 1
				-- its name --> "Rétablir les réglages par défaut"
				if its enabled is true then click it
			end tell
		else
			
			# As I don't have 10.14 or 10.15, I can't get the localized items
			click UI element clickTheLock_loc
			repeat while text field enterPassword_loc of sheet 1 exists
				delay 0.1
			end repeat
			tell tab group 1
				click radio button battery_loc
				click button restoreDefaults_loc
				click radio button powerAdapter_loc
				click button restoreDefaults_loc
			end tell
		end if
	end tell
end tell

tell application "System Preferences" to quit

As I don’t have 10.14 or 10.15, I can’t get the localized items
“Click the lock to make changes.”
“Enter password”
“Battery”
“Restore Defaults”
“Power Adapter”
which don’t exist under 10.13.6

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 8 décembre 2019 21:21:14

In fact the non-localized items are available under 10.13.6 (but in alternate resources)
I edited the script accordingly but I am unable to test it under 10.14 or 10.15

And, here, – the best (and fastest) code, using solution from Shane Stanley’s and maro’s script:


use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreWLAN"

set wRes to powerOffEveryWiFiDevices() -- set WiFi OFF
-- set wRes to powerOnEveryWiFiDevices() of me -- set WiFi ON

tell application "System Preferences" to activate
tell application "System Events" to tell process "System Preferences"
	repeat until window "System Preferences" exists
		delay 0.1
	end repeat
	click button ("Energy
Saver") of scroll area 1 of window "System Preferences"
	repeat until window "Energy Saver" exists
		delay 0.1
	end repeat
	tell window "Energy Saver"
		click UI element "Click the lock to make changes."
		repeat while text field "Enter password" of sheet 1 exists
			delay 0.1
		end repeat
		click radio button "Battery" of tab group 1
		click button "Restore Defaults" of tab group 1
		click radio button "Power Adapter" of tab group 1
		click button "Restore Defaults" of tab group 1
	end tell
end tell
tell application "System Preferences" to quit


on powerOnEveryWiFiDevices()
	set allNames to current application's CWInterface's interfaceNames()'s allObjects() as list
	if allNames = {} then return false
	set powerList to {}
	repeat with i in allNames
		set j to contents of i
		set aInterface to (current application's CWInterface's interfaceWithName:j)
		set wRes to (aInterface's setPower:true |error|:(missing value))
		set aPower to (aInterface's powerOn()) as boolean
		if aPower = false then
			display notification "Error occured in enabling an Wifi deviece ( " & j & " )...."
		end if
		set the end of powerList to aPower
	end repeat
	return ({true} is in powerList) --return whether some WiFi interface is on
end powerOnEveryWiFiDevices

on powerOffEveryWiFiDevices()
	set allNames to current application's CWInterface's interfaceNames()'s allObjects() as list
	if allNames = {} then return false
	set powerList to {}
	repeat with i in allNames
		set j to contents of i
		set aInterface to (current application's CWInterface's interfaceWithName:j)
		set wRes to (aInterface's setPower:false |error|:(missing value))
		set aPower to (aInterface's powerOn()) as boolean
		if aPower = true then
			display notification "Error occured in enabling an Wifi deviece ( " & j & " )...."
		end if
		set the end of powerList to aPower
	end repeat
	return ({true} is in powerList) --return whether some WiFi interface is on
end powerOffEveryWiFiDevices

IMPORTANT: The code lines

click button ("Energy
Saver") of scroll area 1 of window "System Preferences"

should be written as is in my script. Do not change them, because they contain invisible char “\n”. Copy my code with Open this Scriplet in your Editor to avoid errors.

Once again your code run only on recent systems : 10.14 and 10.15.
Under older ones, it fails.
Don’t forget that numerous machines can’t host these new systems.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 9 décembre 2019 10:35:15

I’m sorry to interrupt, but I wrote a simple code snippet of turning “Wi-Fi” on and off without the need to click on “Wi-Fi” in the sidebar beforehand. I think you’re overdoing here (granted, you have excellent knowledge of scripting). The word “Wi-Fi” is the same in every locale and the point is to keep things as simple as a task that requires them is. The task presented by OP is actually very primal and you can do with vanilla AppleScript just fine.