Connect ipad to mac using osascript from GP

I’m using a headless Mac Mini and a wired ipad as the Monitor sometimes the Ipad does not connect and your stuck without a screen.
I’m using this apple script to connect the iPad from GP remove the if blocks

if v = "✓" then
  // already connected
else
click aMenuItem
end if

if you want to toggle it instead of just connect or you could just add click aMenuItem in both if tests, you need to change the name of the iPad to match your own, note it was Damian’s iPad and the script did not like the name so change the iPad name to one without a single quote, you can play with the delays to suit your running system use osascript and the applescript name you saved it as to run the script. works on 15 but should work on earlier os versions.

As ever there are several coders out there who I acknowledge for the code fragments.

tell application "System Settings"
	activate
	delay 3
	reveal pane id "com.apple.Displays-Settings.extension"
	delay 1 -- Adjust based on how quickly your System Settings opens
	tell application "System Events"
		tell first window of application process "System Settings"
			tell group 1 of group 2 of splitter group 1 of group 1
				click pop up button 1
				delay 1 -- Wait for the menu to appear
				tell menu 1 of pop up button 1
					set found to false
					repeat with aMenuItem in menu items
						if name of aMenuItem contains "Mirror or Extend to" then
							set found to true
						end if
						if name of aMenuItem contains "Damian a16" and found then
							set v to ((value of attribute "AXMenuItemMarkChar" of aMenuItem))
							if v = "✓" then
								# already connected
							else
								click aMenuItem
							end if
							exit repeat
						end if
					end repeat
				end tell
			end tell
		end tell
	end tell
end tell
delay 3
set appName to "System Settings"
if application appName is running then
	tell application id (id of application appName) to quit
end if