使用AppleScript实现NAS热文件夹同步遇连接无效问题求助
解决AppleScript文件夹动作同步NAS时Finder崩溃及“Connection is invalid”问题
核心问题拆解
- NAS挂载连接不稳定,脚本执行时挂载点可能临时失效,导致Finder调用
duplicate命令时直接崩溃 - 文件夹动作是后台运行脚本,
display dialog这类UI交互会因权限问题触发异常,进一步拖垮Finder - Finder的文件操作命令在网络共享目录下的兼容性远不如原生shell命令可靠
修复后的完整脚本
-- 日志函数:改用文档目录存储日志,避免后台运行时桌面路径权限问题 on logMessage(message) try set logFilePath to (POSIX path of (path to documents folder)) & "nas_sync_log.txt" set logFile to open for access logFilePath with write permission set eof of logFile to (get eof of logFile) write (current date) & ": " & message & linefeed to logFile close access logFile on error errMsg -- 日志写入失败时,直接写入系统日志 do shell script "logger -t NAS-Sync-Script 'Log Error: " & quoted form of errMsg & "'" end try end logMessage -- 检查NAS挂载点是否有效 on isMounted(mountPath) try do shell script "[ -d " & quoted form of mountPath & " ] && echo 'yes' || echo 'no'" return result is "yes" on error return false end try end isMounted on adding folder items to this_folder after receiving added_items try set nasMountPath to "/Volumes/Art/Input" -- 先校验NAS挂载状态,提前拦截连接错误 if not isMounted(nasMountPath) then logMessage("NAS挂载点无效:" & nasMountPath) display notification "NAS未挂载,同步终止" with title "NAS同步脚本" sound name "Basso" return end if -- 用系统通知替代弹窗,适配后台运行场景 display notification "开始同步" & (count added_items) & "个文件到NAS" with title "NAS同步脚本" -- 用rsync替代Finder的duplicate,网络环境下更稳定 repeat with an_item in added_items set itemPath to POSIX path of an_item do shell script "rsync -aE " & quoted form of itemPath & " " & quoted form of nasMountPath & "/" logMessage("已同步文件:" & itemPath) end repeat on error errMsg number errNum logMessage("错误代码 " & errNum & ": " & errMsg) display notification "同步失败:" & errMsg with title "NAS同步脚本" sound name "Basso" end try end adding folder items to
关键修复说明
- 替换复制工具:用
rsync命令替代Finder的duplicate,rsync对网络共享的容错性更强,不会直接导致Finder崩溃 - 前置挂载检查:执行同步前先确认NAS挂载点存在,提前避免“Connection is invalid”错误
- 调整日志策略:将日志写入文档目录,解决后台脚本访问桌面的权限问题;日志写入失败时自动转存系统日志
- 移除弹窗交互:把
display dialog换成系统通知,适配文件夹动作的后台运行场景,避免权限异常 - 错误反馈优化:同步失败时发送带声音的通知,及时提醒问题
额外优化建议
- 把NAS挂载设置为开机自动连接,勾选“登录时重新连接”,减少挂载点意外断开的概率
- 给rsync命令添加超时参数(比如
--timeout=30),避免因网络卡顿导致脚本长时间阻塞 - 若需要保留手动确认功能,可以改用“点击通知触发同步”的逻辑,但需额外配置后台权限
内容的提问来源于stack exchange,提问作者kirkage
相关产品推荐
相关产品推荐

