AppleScript关机脚本异常求助(Sequoia 15.3.2 + M4 Pro)
AppleScript关机脚本异常问题排查思路
我是AppleScript新手,在Sequoia 15.3.2系统的2025款Apple M4 Pro设备上编写了关机脚本。注释掉shut down命令时,脚本在AppleScript Editor及打包为App运行均正常;启用该命令后,开机时会出现三种异常之一:
- 电脑立即关机
- Apple强制退出对话框显示脚本App仍在运行
- 桌面弹出报错窗口
已精简代码至基础版本但问题依旧,附上代码寻求解决思路:
on run tell application "Finder" to activate tell application "System Events" to set the visible of every process to true try tell application "Finder" set listOfApps to name of every application process whose visible is true and name is not "Finder" and name is not "Script Editor" and name is not {name of me} end tell repeat with appToClose in listOfApps tell application appToClose to quit without saving end repeat on error errStr number errorNumber display dialog "errStr = " & errStr & return & "number = " & number & return & "errorNumber = " & errorNumber buttons {"Quit"} default button 1 return end try tell application "Finder" to close every window tell application "System Events" to shut down end run
排查方向与修复建议
- 修正进程过滤逻辑:代码里
name is not {name of me}的大括号是多余的,会把脚本自身名称变成列表导致过滤失效,改成name is not name of me即可确保脚本进程被排除在关闭列表外。 - 先退出脚本自身再关机:执行关机命令前先让脚本App退出,避免系统关机时它还在运行引发冲突:
quit me delay 1 -- 给系统预留处理退出的时间 tell application "System Events" to shut down - 调整操作时序:把关闭Finder窗口的步骤移到退出其他App之前,或等所有App完全退出后再执行关机,避免窗口关闭和系统关机的时序冲突。
- 改用终端关机命令:如果System Events的
shut down权限有问题,尝试用do shell script调用系统关机命令,记得处理权限:do shell script "shutdown -h now" with administrator privileges - 完善错误捕获:把关机命令也纳入try块,捕获可能的关机错误,方便排查问题:
try tell application "System Events" to shut down on error errMsg number errNum display dialog "关机失败:" & errMsg & " 错误码:" & errNum buttons {"确定"} default button 1 end try - 检查系统权限:给打包后的脚本App开启「完全磁盘访问」权限(系统设置→隐私与安全性→完全磁盘访问),确保它能正常执行系统级操作。
内容的提问来源于stack exchange,提问作者Uncle Bill
相关产品推荐
相关产品推荐

