0

I'm trying to figure out how to create a certain number of folders in a Windows batch file. I want to ask the user how many folder they want, and then use that collected number to loop the asking for names of those folders and make them. Here is what I have so far:

pushd C:\Users\%username%\Desktop

set /p FolderLoop="How many folders?: " 

for /l %%x in (1, 1, %FolderLoop%) do (
    set /p folder="Folder: " %%x
    md %folder% %%x
)

The problem I keep having is that I can not make the folders with the proper collected names. The closest I have gotten so far is creating the right amount of folders, but with sequential numeric names (1,2,3, etc.) based om the FolderLoop variable.

jakenolan52
  • 55
  • 2
  • 11

2 Answers2

2

You need to read any of the hundreds of responses on SO with regard to delayedexpansion.

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Within a block statement (a parenthesised series of statements), REM statements rather than the broken-label remark form (:: comment) should be used because labels terminate blocks, confusing cmd.

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

Magoo
  • 77,302
  • 8
  • 62
  • 84
1

You need delayed expansion:

setlocal enabledelayedexpansion
pushd C:\Users\%username%\Desktop
set /p FolderLoop="How many folders?: " 
for /l %%x in (1, 1, %FolderLoop%) do (
    set /p "folder=Folder: " 
    md "!folder!"
)

(the %%x after set /p does nothing. I removed it. I also removed it from md, you don't need it - except you want the counter be part of the foldername.)

Community
  • 1
  • 1
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • This is it! Thank you! I could tell it was basically ignoring the variable I was trying to call for the folder names. This fixed it! (One thing, just for other readers, delayed in enabledelayedexpansion is missing the e. :) ) – jakenolan52 Jan 20 '16 at 16:07
  • `e` inserted... btw, you can also use `%userprofile%\desktop` – Stephan Jan 20 '16 at 19:33