blog.lnk.si

How to shut down a Mac Mini server by pressing the power button

UPDATE: Initial tests see this script using 1-2% CPU however I haven’t noticed any lag on my (Plex) media centre, so you may want to use caution.

I’ve blogged before about how to shut down a Mac remotely using AppleScript, but this is near useless if, like me, you have a headless Mac Mini running as a media server and the reason you need to restart is that WiFi has dropped out.

There is no way to override what the power button does in OS X, however recently I came across a brilliant piece of AppleScript by MacRumours user Wondercrow which basically polls for the Shut Down dialog which appears when you press the button. Check it.

on idle
  set i to 0
    tell application "System Events"
      -- Get a count of all the windows belonging to
      -- the process
      set numberOfWindows to count windows of process "loginwindow"
      -- Check each window for a "Shut Down" button....
      repeat numberOfWindows times
        set i to i + 1
        -- ....and shut down if found
        if exists button "Shut Down" of window i of process "loginwindow" then
          do shell script "shutdown -h now" password "password" with administrator privileges
        end if
      end repeat
    end tell
    -- How often the script checks for the window
    -- (in seconds). Change it as you see fit.
  return 0.5
end idle

Compile that baby to an Application, and put in your Login Items under Users system preference pane. You may also get an error about “access for assistive devices”. Enable this under the Universal Access system preference pane (it just lets AppleScript inspect the button names).

Leave a Reply