Search code examples
applescriptsubdirectory

Applescript move to a new folder with sequential naming


I've a written the below basic script that checks to see if a folder exists and if it does takes the contents of that folder and adds it to a subfolder.

as you can see in this script generates the sub folder named V1, I wondered if there was a way to sequential name nd generate new folders?

e.g if folder V1 exists Create V2 and move contents

Current Script

--Set image source folder
set SourceFolder to (choose folder with prompt "Choose Base Images:")
set Sourcefoldertext to SourceFolder as text
set FoldertoReplace to Sourcefoldertext & "Images:"

tell application "Finder
    if (exists folder named "Images" in folder SourceFolder) then make new folder in folder FoldertoReplace with properties {name:"V1"}
    if (exists folder named "Images" in folder SourceFolder) then set fileList to every file of folder FoldertoReplace  
    if not (exists folder named "Images" in folder SourceFolder) then make new folder in folder SourceFolder with properties {name:"Images"}    
    if (exists folder named "V1" in folder FoldertoReplace) then set VersionFolder to the folder named "V1" in the folder FoldertoReplace   
    if (exists folder named "V1" in folder FoldertoReplace) then return move the fileList to the VersionFolder'
end tell

Thanks P


Solution

  • The existing solution is great, but I thought I'd add an alternative just for some variety.

    This handler uses System Events and a recursive function call to check for existing folder versions. The parameter targetFolderPath can be an alias object, a posix path, or an HFS path.

    to createSequentialVersionFolder at targetFolderPath given name:dir : "V"
        local targetFolderPath, dir
    
        script
            property fp : targetFolderPath
            property dirname : dir
    
            to checkVersion(i)
                tell application "System Events"
                    if exists the folder named (dirname & i) ¬
                        in the folder named fp then ¬
                        return my checkVersion(i + 1)
    
                    make new folder at folder named fp ¬
                        with properties ¬
                        {name:dirname & i}
                end tell
            end checkVersion
        end script
    
        result's checkVersion(1)
    end createSequentialVersionFolder
    

    To use:

    createSequentialVersionFolder at "~/Desktop"
    

    or:

    createSequentialVersionFolder at (path to desktop folder)