Search code examples
loopsbatch-fileif-statementfile-exists

I need a bit of advice on a Batch file If exists then followed with a loop


I am trying to create a batch file that copies files from one folder to a new one that it creates, (mkdir "new folder") and renames the folder 1. If folder 1 already exists then name it folder 2. This would loop by adding 1 to the folder name until that folder did not exist and then copy the files to that folder.

Here is my code so far, I have searched the site for some direction, but am not finding anything specifically doing this. Any help would be much appreciated.

The areas I need help with are set in the program with :: comments

@ECHO OFF
cd c:\
set a=1
mkdir C:\"New folder"
ren "C:\New folder" "%a%"

:: if the folder already exists then

set /a "a=%a%+1"
ren "C:\New folder" "%a%"

:: I need this to loop till the folder does not already exist and then can be renamed.
:: Then I need to files located in "c:\folder_to_copy" to copy into the newly named folder

robocopy "c:\folder_to_copy" "c:\%a%"

Solution

  • That's quite easy:

    set i=0
    :loop
    set /a i+=1
    md "%i%" 2>nul || goto :loop
    echo created %i%
    

    || works as "if previous command failed (could not create the folder) then"

    PS: make sure there is write permission - else this turns into an endless loop (not able to create folders)

    or adapted to your use-case: check if the folder exists until you hit one that doesn't:

    set i=0
    :loop
    set /a i+=1
    if exist "%i%\" goto :loop
    ren "c:\new folder" "%i%"