AppleScript - 将子文件夹中包含的所有文件移动到顶级文件夹

AppleScript - Move all the files contained in subfolder to a top folder

我正在寻找对当前脚本的编辑。我需要的是将所有文件从子文件夹(递归地)移动到一个顶级文件夹,但是如果存在同名文件,请创建一个新的顶级文件夹并在那里继续,这就是我目前所拥有的:

tell application "Finder"
    try
        set Random_name to random number from 100 to 9999
        set theTopFolder to (choose folder)
        set theFiles to a reference to every file of (entire contents of folder theTopFolder)
        set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files"}
        move theFiles to theNewFolder
    on error
        set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files" & Random_name}
        move theFiles to theNewFolder
    end try


end tell

要清楚路径的结构不是:

Mainfolder/subfolder/file.xxx 但是 Mainfolder/subfolder/sulbfolder2/subfolder3/....100/file.xxx 所以脚本需要递归地工作但它会在文件存在时停止名字

当存在同名文件时,我的编辑会创建一个包含 Flattened Files+随机数的新文件夹,但是当移动另一个同名文件时,脚本会因错误而停止,而不是继续创建新的 Flattened Files +randonnumber 文件夹。有什么想法吗?

谢谢

您的脚本没有使用递归,它只是让 Finder 获取所有文件。您收到的其他错误是因为您试图再次移动整个文件列表。

一种解决方案是遍历文件项,边走边测试重复项,并根据需要创建新文件夹。以下脚本只是将重复项移动到添加的文件夹(请注意,错误仍会停止脚本)。我不知道你是如何对文件列表进行排序的,所以我添加了一行来取消注释以继续将文件项移动到添加的文件夹中。

set theTopFolder to (choose folder)
tell application "Finder"
    set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files"}
    set theFiles to every file of (entire contents of folder theTopFolder) as alias list
    repeat with aFile in theFiles
        if file ((theNewFolder as text) & (name of aFile)) exists then -- use added folders for duplicates
            set counter to 1
            set done to false
            repeat until done
                set suffix to text -2 thru -1 of ("000000" & counter) -- leading zeros for sorting
                set alternateFolder to (theTopFolder as text) & "Flattened Files" & space & suffix
                tell me to (do shell script "mkdir -p " & quoted form of POSIX path of alternateFolder) -- make new folder as needed
                if file (alternateFolder & ":" & (name of aFile)) exists then -- continue to next one
                    set counter to counter + 1
                else
                    move aFile to folder alternateFolder
                    # set theNewFolder to folder alternateFolder -- uncomment to continue moving here after a duplicate
                    set done to true
                end if
            end repeat
        else
            move aFile to folder (theNewFolder as text)
        end if
    end repeat
end tell