How do I increment a folder name using Windows batch?

Solution 1:

Here is a solution that will always work, even if there are gaps in the numbers. The folder number will always be 1 greater than the current max number.

@echo off
setlocal enableDelayedExpansion
set "baseName=New_Folder"
set "n=0"
for /f "delims=" %%F in (
  '2^>nul dir /b /ad "%baseName%*."^|findstr /xri "%baseName%[0-9]*"'
) do (
  set "name=%%F"
  set "name=!name:*%baseName%=!"
  if !name! gtr !n! set "n=!name!"
)
set /a n+=1
md "%baseName%%n%"

Solution 2:

with that you will be able to count the number of occurence of "New_Folder*" and create one with the next number.

@echo off
set /a count=0

for /d %%d in (New_Folder*) do (
    set /a count+=1
)

set /a count+=1

mkdir New_Folder%count%

Note that the best way would be to find the largest number at the end of New_Folder, but Windows Batch is very limitative and I'm a Linux guy!

EDIT : After about one hour of googling and testing :

@echo off

setlocal EnableDelayedExpansion

set max_number=0

for /d %%d in (New_Folder*) do (
    set current_directory=%%~nxd

    call:StrLength name_length !current_directory!
    call:Substring directory_number,!current_directory!,10,!name_length!

    if !directory_number! gtr !max_number! (
        set max_number=!directory_number!
    )
)

set /a max_number+=1

mkdir New_Folder%max_number%

:Substring
::Substring(retVal,string,startIndex,length)
:: extracts the substring from string starting at startIndex for the specified length 
 SET string=%2%
 SET startIndex=%3%
 SET length=%4%

 if "%4" == "0" goto :noLength
 CALL SET _substring=%%string:~%startIndex%,%length%%%
 goto :substringResult
 :noLength
 CALL SET _substring=%%string:~%startIndex%%%
 :substringResult
 set "%~1=%_substring%"
GOTO :EOF

:StrLength
::StrLength(retVal,string)
::returns the length of the string specified in %2 and stores it in %1
set #=%2%
set length=0
:stringLengthLoop
if defined # (set #=%#:~1%&set /A length += 1&goto stringLengthLoop)
::echo the string is %length% characters long!
set "%~1=%length%"
GOTO :EOF

Note, the command line return me an error "The syntax of the command is incorrect." but everything works so I'll let you find why... New folder is created regardless of the order of directories or if they start at 1 or not :) Hope you'll enjoy!