Toggle Bluetooth with Applescript

Written by Haydn Williams

I’ve just written a little Applescript to toggle the Bluetooth power on my MacBook on or off. It doesn’t take any parameters or anything, it literally just toggles it off if it’s already on, or on if it’s already off. The script looks like this:

#! /usr/bin/osascript
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# *  Author:	Haydn Williams
# *  URL:	http://www.haydnwilliams.com
# *  Date:	March 2008
# *  Script:	toggleBluetooth.scpt
# *  Purpose:	Toggle bluetooth status
# *  Useage:	toggleBluetooth.scpt
#  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
tell application "System Preferences"
	activate
	set current pane to pane "com.apple.preferences.Bluetooth"
	try
		tell application "System Events"
			tell process "System Preferences"
				click checkbox "On" of window "Bluetooth"
			end tell
		end tell
	on error
		display dialog "Failed to toggle bluetooth."
	end try
	tell application "System Preferences" to close the first window
end tell


You can download the compiled script fromĀ here. Please note that you’ll need to ‘Enable GUI Scripting‘ in the AppleScript Utility (you can find it in the AppleScript folder of Applications). To run the script, just double-click on it. Please note that this will probably only work on English language systems, but should be easy enough to alter.

1 thought on “Toggle Bluetooth with Applescript

  1. A Chess says:

    Really useful, thanks!
    I cobbled together a script to run iSync as well.

    tell application “iSync”
    if not syncing then
    my turnBlueToothOn()
    synchronize
    repeat while syncing
    delay 1
    end repeat
    my turnBlueToothOff()
    quit
    end if
    end tell

    on turnBlueToothOn()
    tell application “System Preferences”
    activate
    tell application “Finder”
    set visible of every process whose visible is true and name is “System Preferences” to false
    end tell
    set current pane to pane “com.apple.preferences.Bluetooth”
    try
    tell application “System Events”
    tell process “System Preferences”
    if enabled of checkbox “Discoverable” of window “Bluetooth” = false then
    click checkbox “On” of window “Bluetooth”
    end if
    end tell
    end tell
    on error
    display dialog “Failed to toggle bluetooth.”
    end try
    end tell
    end turnBlueToothOn

    on turnBlueToothOff()
    tell application “System Preferences”
    set current pane to pane “com.apple.preferences.Bluetooth”
    try
    tell application “System Events”
    tell process “System Preferences”
    click checkbox “On” of window “Bluetooth”
    end tell
    end tell
    end try
    end tell
    tell application “System Preferences” to quit
    end turnBlueToothOff

No Comments