如何通过AppleScript修改plist实现Dock指定应用的添加与移除
Dock应用增删AppleScript解决方案
报错原因
你写的脚本报错是因为com.apple.dock.plist中没有直接以应用名作为键的顶级属性,所有固定到Dock的应用都存储在persistent-apps数组下,每个数组元素是字典结构,应用名称存放在字典内tile-data的file-label字段中,直接查找顶级的Firefox.app键自然会找不到对应的属性项。
功能实现脚本
删除Dock指定应用
-- 替换为你要删除的应用名称,无需带.app后缀 set targetApp to "Firefox" set dockPlist to (path to preferences folder as text) & "com.apple.dock.plist" tell application "System Events" tell property list file dockPlist set appList to value of property list item "persistent-apps" set filteredList to {} repeat with appItem in appList if |file-label| of (|tile-data| of appItem) ≠ targetApp then copy contents of appItem to end of filteredList end if end repeat set value of property list item "persistent-apps" to filteredList end tell end tell -- 重启Dock生效 do shell script "killall Dock"
向Dock添加指定应用
推荐直接用shell命令实现,语法更简单,只需替换路径为目标应用的实际路径即可:
defaults write com.apple.dock persistent-apps -array-add "<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>file:///Applications/Firefox.app</string><key>_CFURLStringType</key><integer>15</integer></dict></dict></dict>" && killall Dock
如果需要用纯AppleScript实现,可以用以下代码:
-- 替换为目标应用的绝对路径 set appPath to "/Applications/Firefox.app" set dockPlist to (path to preferences folder as text) & "com.apple.dock.plist" tell application "System Events" set targetApp to POSIX file appPath as alias set appName to name of targetApp -- 构造标准Dock应用项结构 set newItem to {|tile-data|:{|file-label|:appName, |file-data|:{|_CFURLString|:("file://" & POSIX path of targetApp), |_CFURLStringType|:15}}, |tile-type|:"file-tile"} -- 写入plist tell property list file dockPlist set appList to value of property list item "persistent-apps" copy newItem to end of appList set value of property list item "persistent-apps" to appList end tell end tell do shell script "killall Dock"
注意事项
- 操作前可先备份Dock配置:执行命令
defaults export com.apple.dock ~/dock_backup.plist,需要恢复时执行defaults import com.apple.dock ~/dock_backup.plist && killall Dock即可 - 应用名称、路径需和实际完全匹配,大小写敏感
- 系统内置应用(如访达、信息)的存储路径为
/System/Applications/,添加时需填写对应完整路径
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

