error "System Events got an error: Can’t get application process \"System Preferences\"."
This works for me using the latest version of macOS Mojave.  This code may need to be adjusted To work with the current version of your operating system;

try
    if application "System Preferences" is running then do shell script "killall 'System Preferences'"
end try
repeat until application "System Preferences" is not running
    delay 0.1
end repeat
tell application "System Preferences"
    reveal anchor "Main" of pane id "com.apple.preferences.Bluetooth"
end tell

tell application "System Events" to tell application process "System Preferences"
    repeat while not (exists of UI element "Turn Bluetooth Off" of window "Bluetooth")
        delay 0.1
    end repeat
    click UI element "Turn Bluetooth Off" of window "Bluetooth"
    repeat while not (exists of UI element "Turn Bluetooth On" of window "Bluetooth")
        delay 0.1
    end repeat
end tell

try
    if application "System Preferences" is running then do shell script "killall 'System Preferences'"
end try