Create folder in . bat with variable name

Asked

Viewed 2,094 times

1

I am trying to create folders on my DESKTOP "automatically" with the name I put, when the program is running.

1° I need to set the amount of folders (%number_of_agents%);

2° Get in the way of my DESKTOP and create a folder(%Calls%) and enter this folder(cd Calls);

@echo off
::Type the numbers of PATHS that you want to create

set /p number_of_agents= "Type the number of agents: "
echo.
echo %number_of_agents%
echo.

cd %caminho_para_meu_desktop%
md "Calls"
cd Calls

3° Loop up to the amount predetermined by the variable number_of_agents

::
for /l %%a in (1,1, %number_of_agents%) do 
(
set /p PA_login= "PA login: "
md "%PA_login%"
)

4° When I input variable Pa_login, cannot create folder with name

pause >nul

2 answers

6


Your code has nothing wrong with logic, it’s a syntax error and the lack of use of ENABLEDELAYEDEXPANSION to the for with set, in the syntax error you broke a line after the do of your for that couldn’t have broken, you did it:

for /l %%a in (1,1, %number_of_agents%) do
(

When should this be:

for /l %%a in (1,1, %number_of_agents%) do (

If you use the ( in the next line cmd will not recognize as sequence of the command, because in CMD the parentheses are the way to pass the instruction as a block, but the instruction needs to be part of the for and not being on the same line will not understand as such, after all BAT is not quite a "programming language" as "other", but rather a sequence of commands that accepts some syntaxes, see what happens with your script:

C:\>C:\Users\usuario\Desktop\a.bat

C:\>set number_of_agents=2
A sintaxe do comando está incorreta.
C:\>for /l %a in (1,1, 2) do
C:\>

Noticed the message A sintaxe do comando está incorreta.? Now with the block (the parentheses) starting on the same line:

C:\>C:\Users\new_g\Desktop\a.bat

C:\>set number_of_agents=2

C:\>for /L %a in (1 1 2) do (echo %a )

C:\>(echo 1 )
1

C:\>(echo 2 )
2

C:\>pause

Using set within a for

To use the set within the is necessary to enable the ENABLEDELAYEDEXPANSION, see an example without:

@echo off
set TESTE=0

for %%v in (1 2 3) do (
  set /p TESTE=Digite algo: 
  echo Resposta:  %TESTE%
)

pause

It will always emit "Answer: 0" (zero, which is the initial value), then doing this (change the signals %% by exclamations), thus:

@echo off
setlocal EnableDelayedExpansion
set COUNT=0

for %%v in (1 2 3 4) do (
  set /p TESTE=Digite algo: 
  echo Resposta: !TESTE!
)

pause

And in the end it can disable with SETLOCAL DisableDelayedExpansion

as explained in: https://ss64.com/nt/delayedexpansion.html

1

You’re a little confused to understand your question...


@echo off & title <nul & title .\%0 && set "number_of_agents="

:loop
set/p "-= Type the numbers of PATHS that you want to create: " 
set /p "number_of_agents= Type the number of agents: " && rem/

<con: echo/%number_of_agents%|findstr [0-9] && cd.||goto :loop

pushd "%userprofile%\desktop" && md .\Calls 2>nul &cd /d Calls

for /l %%a in (1 1 %number_of_agents%
)do set /p "PA_login=PA login: " && cmd /v/s/r md "!PA_login!"

tree /a /f . && popd && timeout -1 >nul & exit /b || goto :EOF

  • Response code with comments:
rem :: habilita a inibição da saída dos comando na execução do bat
@echo off 

rem :: remove o titula da janela e atribui ao nome do arquivo bat
title <nul & title .\%0 

rem :: remove existente ou não a variável umber_of_agents
set "number_of_agents="

rem :: lable para verificar se o input contem ou não números
:loop

rem :: apenas uma forma de printar caracteres na tela sem quebrar  linha
set/p "-= Type the numbers of PATHS that you want to create: " 

rem :: seta variável number_of_agents e exibe o text entre "aspas"
set /p "number_of_agents= Type the number of agents: " && rem/

rem :: o mesmo que set /p e sem salvar valor/variável, mesmo que echo 
<con: echo/%number_of_agents%

rem :: procura na saída do comando anterior ocorrência 1+ números (também usado pra imprimir entrada na tela)
|findstr [0-9] 

rem :: usado para gerar quebra de linha caso encontrou número(s) na execução anterior 
&& cd.

rem :: se ação anterior (buscar números na variável %number_of_agents%) retorne falso, volta para label loop
||goto :loop

rem :: por a pasta atual salva para retornar (via popd) e traz para pila a pasta "%userprofile%\desktop"
pushd "%userprofile%\desktop"

rem :: caso a ação anterior retorne verdadeiro (traz para pila a pasta "%userprofile%\desktop") vai criar a pasta .\Call e entar nela, já ignorando a existência/saída de erro (mais rápido que usar if, n exist criar, if tem entra nela)
&& md .\Calls 2>nul & cd /d Calls

rem :: faz loop de 1 em 1 até o número informado na variável number_of_agents
for /l %%a in (1 1 %number_of_agents%)do 

rem :: imprimir na tela a entrada para PA_login e após a inserção do usuário, vai criar a pasta informado no input 
set /p "PA_login=PA login: " && cmd /v/s/r md "!PA_login!"

rem :: se o input foi executado, vai executar a ação de criae a pasta com o nome informado para variável PA_login
&& cmd /v/s/r md "!PA_login!"

rem :: vai listar as pasta criadas em formato de arvore (tree)
tree /a /f . 

rem :: retornar para a pasta onde originalmente (salvo por pushd) o bat foi executado
popd 

rem :: uma opção de pause, faz um timeout/pause, só aguardar entrada do teclado para continuar
timeout -1 
rem :: ai sair do bat, e para os mais paracônicos, se não sair vai para :eof (end of file|fim do arquivo)
&& exit /b || goto :EOF

Obs.: That’s what I understand, if not this, use the comments...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.