AppleScript重命名文件时触发-10006及-1728错误求助
AppleScript批量重命名PDF文件报错解决方案
问题背景
尝试用两段AppleScript代码选择文件夹并重命名其中的PDF文件,运行报错,已确认文件夹有读写权限。
第一段代码及错误
on run set Source to (choose folder with prompt "Pick the folder containing the images to process:") as alias set newName to "new file name.pdf" tell application "Finder" try set myFile to name of every file of Source as string set name of myFile to newName as string on error err log ("Error in procedure: " & (err as text)) end try end tell end run
运行返回错误 -10006。
修改后的代码及错误
修改第7行后代码:
on run set Source to (choose folder with prompt "Pick the folder containing the images to process:") as alias set newName to "new file name.pdf" tell application "Finder" try set myFile to name of every file of Source as string set name of file myFile to newName as string on error err log ("Error in procedure: " & (err as text)) end try end tell end run
错误代码变为 error number -1728 from file "AD-3.HRYN.pdf",错误说明:引用的对象不存在,属于运行时解析错误。控制台提示:Error in procedure: Il est impossible de régler name of "AD-3.HRYN.pdf" à "new file name.pdf".
问题原因
- 第一段代码中,
set myFile to name of every file of Source as string获取的是所有文件名的列表,直接给这个列表设置name属性,Finder无法识别,导致-10006操作无法完成的错误。 - 修改后的代码里,
file myFile试图用文件名列表定位文件,但Finder无法通过列表匹配到具体文件;同时如果文件夹内有多个文件,重复设置同一名称也会引发冲突,最终出现-1728对象不存在的错误。
解决代码
批量重命名(按序号区分避免重名)
on run set Source to (choose folder with prompt "选择包含PDF文件的文件夹:") as alias tell application "Finder" -- 仅筛选PDF文件 set pdfFiles to every file of Source whose name extension is "pdf" -- 循环给每个PDF加序号重命名 repeat with i from 1 to count of pdfFiles set currentFile to item i of pdfFiles set name of currentFile to "new file name " & i & ".pdf" end repeat end tell end run
单个PDF重命名(确保文件夹内仅一个PDF)
on run set Source to (choose folder with prompt "选择包含PDF文件的文件夹:") as alias set newName to "new file name.pdf" tell application "Finder" try set targetFile to first file of Source whose name extension is "pdf" set name of targetFile to newName on error err log ("错误信息: " & (err as text)) end try end tell end run
关键说明
- 通过
whose name extension is "pdf"筛选目标文件,避免误改其他类型文件。 - 批量重命名必须添加序号或唯一标识,否则多个文件使用同一名称会触发系统报错。
- 操作文件时直接引用Finder的
file对象,而非仅使用文件名,确保Finder能准确定位到目标文件。
内容的提问来源于stack exchange,提问作者D4vi9
相关产品推荐
相关产品推荐

