如何用AppleScript与文件夹动作获取被移动文件的原位置
实现检测移动文件来源位置的文件夹动作AppleScript
原代码中的previous location属性在Finder中并不存在,这是导致报错的核心原因。要获取文件移动前的来源位置,我们可以通过查询Spotlight元数据中的kMDItemPreviousLocation字段来实现,以下是正确的代码实现:
on adding folder items to this_folder after receiving added_items try repeat with current_item in added_items -- 获取文件的POSIX路径,用于执行mdls命令 set posix_path to POSIX path of current_item -- 调用mdls命令获取kMDItemPreviousLocation元数据 set previous_location_raw to do shell script "mdls -name kMDItemPreviousLocation -raw " & quoted form of posix_path -- 解析元数据结果,提取路径 if previous_location_raw is not equal to "(null)" then -- 去除元数据中的file://前缀和引号 set oldPath to text 8 thru -2 of previous_location_raw -- 转换为Finder可识别的路径格式 set oldPath to POSIX file oldPath as alias tell application "Finder" display dialog "文件: " & name of current_item & return & "原位置: " & POSIX path of oldPath end tell else display dialog "文件: " & name of current_item & return & "无法获取原位置(可能是新建或复制而非移动)" end if end repeat on error errorMessage number errorNumber display dialog "错误信息: " & errorMessage & ", 错误代码: " & errorNumber end try end adding folder items to
关键说明
- 该方法依赖Spotlight索引,确保目标文件已被Spotlight索引(本地文件默认都会被索引)。
- 如果文件是复制而非移动过来的,
kMDItemPreviousLocation会返回(null),因为复制操作不会记录原位置到该元数据字段。 - 代码遍历
added_items,支持同时处理多个被移动的文件。
内容的提问来源于stack exchange,提问作者domac
相关产品推荐
相关产品推荐

