How can I automatically run an AppleScript on shutdown or logout?
Launch agents can be used for this. See this tutorial on MacScipter. If you are not familiar with the process, Lingon offers a simple interface to create the file. Here is an example to launch a script named ZuluDeltaNiner.scpt on login.

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
   &lt;key&gt;Label&lt;/key&gt;
   &lt;string&gt;com.paul.applescript_Launchd&lt;/string&gt;
   &lt;key&gt;ProgramArguments&lt;/key&gt;
   &lt;array&gt;
       &lt;string&gt;osascript&lt;/string&gt;
       &lt;string&gt;/ZuluDeltaNiner.scpt&lt;/string&gt;
   &lt;/array&gt;
   &lt;key&gt;QueueDirectories&lt;/key&gt;
   &lt;array/&gt;
   &lt;key&gt;RunAtLoad&lt;/key&gt;
   &lt;true/&gt;
   &lt;key&gt;StartOnMount&lt;/key&gt;
   &lt;false/&gt;
   &lt;key&gt;WatchPaths&lt;/key&gt;
   &lt;array/&gt;
&lt;/dict&gt;
&lt;/plist&gt;