ketchfrayz
ketchfrayz

Reputation: 13

How to increment folder name

I have a batch file that creates a folder named TempIOFile. On subsequent runs it should recognize that the TempIOFile folder exists and create an incremented version of the folder(TempIOFile1, TempIOFile2, and so on).

I have code that works to increment the file:

set "baseName=TempIOFile"
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%"

However when I try to use an IF EXIST statement I get an error: The filename, directory name, or volume label syntax is incorrect.

IF EXIST %userprofile%\desktop\TempIOFile (
set "baseName=TempIOFile"
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%"
) ELSE (
MKDIR %userprofile%\desktop\TempIOFile

)

I'm not sure why this is not working. The TempIOFile is created but on subsequent runs the incremented versions are not. Can anyone help?

Upvotes: 1

Views: 232

Answers (1)

Squashman
Squashman

Reputation: 14290

Should be as simple as this. Unless I am not understanding your question.

 @echo off

 set "Num="
 :loop
 If EXIST "%userprofile%\desktop\TempIOFile%Num%\" (
    set /A Num+=1
    goto loop
 )

 md "%userprofile%\desktop\TempIOFile%Num%\"

Or this.

@echo off
set "Num="
:loop
(md "%userprofile%\desktop\TempIOFile%Num%\" > nul 2>&1) || (set /A Num+=1 & goto loop)

Upvotes: 1

Related Questions