You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mac OS Automator中设置变量,实现拖放文件夹自动重命名

问题:修改AppleScript支持拖放文件夹自动重命名

我对AppleScript和Automator的使用经验有限,之前靠反复试错拼出了能满足需求的脚本。现在要帮别人整理硬盘崩溃后恢复的200K+无完整备份的照片,需要按主题自动分组到对应文件夹。现有一个基于AppleScript的Automator应用,能把文件夹重命名为其中首个非文件夹项的文件名,但需要手动选择文件夹;希望改成支持将文件夹拖放到应用上自动运行,不用手动操作。现有脚本如下:

tell application "Finder"
    -- select folder
    set theFolder to choose folder with prompt "Select a folder to rename based on its first file:"
    
    -- Get the first file
    set firstFile to first item of theFolder whose kind is not "Folder"
    
    -- Get the name of the first file 
    set fileName to name of firstFile
    set fileExtension to name extension of firstFile
    set fileBaseName to text 1 through ((length of fileName) - (length of fileExtension) - 1) of fileName
    
    -- Rename the folder
    set name of theFolder to fileBaseName
end tell

修改后的脚本

下面是适配拖放功能的版本,同时支持单次拖放多个文件夹:

on run {theItems}
    tell application "Finder"
        repeat with itemRef in theItems
            -- 确认当前对象是文件夹
            if class of itemRef is folder then
                set theFolder to itemRef
                -- 查找文件夹内第一个非文件夹项
                set fileList to every item of theFolder whose kind is not "Folder"
                if fileList is not {} then
                    set firstFile to first item of fileList
                    -- 提取文件的基础名称(去掉扩展名)
                    set fileName to name of firstFile
                    set fileExtension to name extension of firstFile
                    if fileExtension is not "" then
                        set fileBaseName to text 1 through ((length of fileName) - (length of fileExtension) - 1) of fileName
                    else
                        -- 处理无扩展名的文件
                        set fileBaseName to fileName
                    end if
                    -- 重命名文件夹
                    set name of theFolder to fileBaseName
                end if
            end if
        end repeat
    end tell
end run

关键改动说明

  • 移除手动选择逻辑:删掉了原脚本里的choose folder代码,改用on run {theItems}接收拖放进来的对象列表,拖放的文件夹会自动传入theItems参数。
  • 支持多文件夹批量处理:加入repeat循环,遍历所有拖放进来的对象,一次拖多个文件夹也能逐个处理。
  • 增加容错判断:
    • 先确认当前对象是文件夹,避免处理拖放的文件时出错;
    • 检查文件夹内是否存在非文件夹项,空文件夹或者全是子文件夹的情况会跳过,防止脚本报错;
    • 处理无扩展名的文件,避免原脚本在遇到这类文件时计算索引出错。

Automator配置注意事项

要让这个脚本在Automator里正常工作,需要:

  1. 打开Automator,新建一个应用程序类型的项目;
  2. 添加「运行AppleScript」动作,把上面的新脚本替换进去;
  3. 保存应用程序,之后直接把要处理的文件夹拖到这个应用图标上就能自动执行。

内容的提问来源于stack exchange,提问作者user3376920

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:57:13