.Bat code only creates file for one set of data entered - batch-file

I want to create a bat file asking for a user input which will ask for some choices:
#echo off
MKDIR D:\BatFiles\File
SET /P Output="D:\BatFiles\File"
ECHO Select Task
ECHO ==========
#echo off
title Task List Creator
:homescreen
ECHO
Echo 1.) Create Notepad Task File
Echo 2.) Exit
Echo.
set /p input=Type Choice :
if "%input%"=="1" goto getInfo
if "%input%"=="2" exit
Pause
:getInfo
set /p VarOne=Enter Type:
set /p VarTwo=Enter Number:
set /p VarThree=Enter Name:
echo Task Type=%VarOne% >> %Output%\test.txt
echo Task Number=%VarTwo% >> %Output%\test.txt
echo Task Name=%VarThree% >> %Output%\test.txt
echo Entry successfully written
Pause
goto finished
:finished
echo Do you want to create a new set of entry?
set /p response= Y or N?
if "%response%"=="Y" goto getInfo
if "%response%"=="N" goto homescreen
--The problem with this code is that I want to create more than 2 entries. This code only creates an output file if user has only one set of entries. If user creates 2 or more, the output file is not created and data entered appears only when user runs the bat file again and only enters one set of data. Sorry about the lame question, I'm just a batch file beginner here.

Look on this code:
#echo off
title Task List Creator
setlocal EnableExtensions EnableDelayedExpansion
set "OutputFolder=D:\BatFiles\File"
set FileNumber=0
:HomeScreen
cls
echo Select Task
echo ===========
echo.
echo 1 ... Create Notepad Task File
echo 2 ... Exit
echo.
set "Input=2"
set /P "Input=Your choice: "
if "!Input!"=="1" goto PrepareTaskFile
if "!Input!"=="2" endlocal & goto :EOF
goto HomeScreen
:PrepareTaskFile
set /A FileNumber+=1
set "OutputFile=%OutputFolder%\test%FileNumber%.txt"
if exist "%OutputFile%" del "%OutputFile%"
:GetInfo
echo.
set "VarOne="
set "VarTwo="
set "VarThree="
:EnterType
set /P "VarOne=Enter type: "
if not defined VarOne goto EnterType
:EnterNumber
set /P "VarTwo=Enter number: "
if not defined VarTwo goto EnterNumber
:EnterName
set /P "VarThree=Enter name: "
if not defined VarThree goto EnterName
if not exist "%OutputFolder%" mkdir "%OutputFolder%"
echo Task Type=!VarOne!>>"%OutputFile%"
echo Task Number=!VarTwo!>>"%OutputFile%"
echo Task Name=!VarThree!>>"%OutputFile%"
echo.
echo Entry successfully written.
echo.
pause
echo.
echo Do you want to create a new set of entry?
echo.
set "Response=N"
set /P "Response=Y or N? "
if /I "!Response!"=="Y" goto GetInfo
goto HomeScreen
The environment variable on prompt keeps its current value if the user just hits RETURN or ENTER. Therefore it is advisable to define a default value or undefine a variable before prompting the user.
The entered strings assigned to the variables are referenced with usage of delayed expansion in case of user enters something not expected which could result in a syntax error and therefore exit of batch processing on referencing the entered strings with immediate expansion. For example a string comparison would fail with a syntax error if the user enters a string with a double quote.
See How to set environment variables with spaces? why using double quotes as it can be seen here on set "variable=string value" and set /P "variable=prompt text".
The space character left of redirection operator >> in code of question would be also written into the file. This should be avoided by removing it and reference the variables with delayed expansion in case of the variable value is a number with value 1, 2, 3, ... to avoid a wrong handle redirection, see the Microsoft article about Using command redirection operators.
On usage of set /P for a menu instead of command choice it must be always taken into account that the user enters something not suggested. So if the user enters on first prompt whether 1 nor 2, there must be code which defines the behavior on the invalid input.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cls /?
del /?
echo /?
endlocal /?
goto /?
if /?
mkdir /?
pause /?
set /?
setlocal /?
title /?
See also answer on Single line with multiple commands using Windows batch file for an explanation of & between endlocal and goto :EOF.

Related

How to prompt a user multiple times by a batch file with multiple user inputs?

I want to change the serial number and product number of about 250 servers (they are not correct at the moment). I know the command that I need to use, but I need to be able to input certain options in to that command and then run it.
The options I need are:
A prompt for selecting the update of the serial or the product number
Multiple prompts for actual serial number, an IP address, a user name and password on having selected before the update of the serial number
Multiple prompts for actual product number, an IP address, a user name and password on having selected before the update of the product number
The command I wish to run via the batch file is:
asu64 set SYSTEM_PROD_DATA.SysInfoSerialNum XXXXXXX --host XXX.XXX.XXX.XXX --user XXXX --password XXXX
The XXX is a user defined input. I'd also like for completion and then go back to the initial selection menu.
Here is what I have done so far. (Please excuse the simplicity of it. I am very new to this stuff.)
#ECHO OFF
ECHO Test Code
ECHO.
ECHO 1.Serial Number
ECHO 2.Product Name
ECHO.
CHOICE /C 12 /M "Enter your choice:"
ECHO.
IF CHOICE 1 GOTO SerialNumber
IF CHOICE 2 GOTO ProductName
:SerialNumber
ECHO Serial Number
GOTO End
:ProductNumber
ECHO Product Number
GOTO End
PAUSE
Many thanks for any help you can offer.
There could be used for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "IpAddress="
set "NameUser="
set "Password="
:MainMenu
cls
echo/
echo 1 ... Serial number
echo 2 ... Product number
echo E ... Exit
echo/
%SystemRoot%\System32\choice.exe /C 12E /N /M "Enter your choice:"
if errorlevel 3 exit /B
if not errorlevel 1 goto MainMenu
echo/
if errorlevel 2 goto ProductNumber
set "NumberText=serial"
set "NumberOption=SYSTEM_PROD_DATA.SysInfoSerialNum"
goto NumberPrompt
:ProductNumber
set "NumberText=product"
set "NumberOption=SYSTEM_PROD_DATA.SysInfoProductNum"
:NumberPrompt
set "NumberValue="
set /P "NumberValue=Please enter %NumberText% number: " || goto NumberPrompt
set "NumberValue=%NumberValue:"=%"
if not defined NumberValue goto NumberPrompt
echo/
if defined IpAddress (set "Default= [%IpAddress%]") else set "Default="
:IpPrompt
set /P "IpAddress=Please enter IP address%Default%: "
if not defined IpAddress goto IpPrompt
set "IpAddress=%IpAddress:"=%"
if not defined IpAddress goto IpPrompt
echo/
if defined NameUser (set "Default= [%NameUser%]") else set "Default="
:NamePrompt
set /P "NameUser=Please enter user name%Default%: "
if not defined NameUser goto NamePrompt
set "NameUser=%NameUser:"=%"
if not defined NameUser goto NamePrompt
echo/
if defined Password (set "Default= [%Password%]") else set "Default="
:PasswordPrompt
set /P "Password=Please enter password%Default%: "
if not defined Password goto PasswordPrompt
set "Password=%Password:"=%"
if not defined Password goto PasswordPrompt
echo/
"%~dp0ASU64.exe" set %NumberOption% "%NumberValue%" --host "%IpAddress%" --user "%NameUser%" --password "%Password%"
echo/
if not errorlevel 1 (
echo The update of the %NumberText% number "%NumberValue%" was successful.
) else echo ERROR: The update of the %NumberText% number "%NumberValue%" failed!
echo/
%SystemRoot%\System32\choice.exe /C CE /N /T 10 /D C /M "Press C to continue or E to exit ..."
if not errorlevel 2 goto MainMenu
endlocal
The executable ASU64.exe is referenced with full path of the batch file which means the executable must be always in the same directory as the batch file. The current directory of cmd.exe processing the batch file does not matter in this case.
Please read the following answers for the explanation of the code:
How does the Windows Command Interpreter (CMD.EXE) parse scripts?
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
Single line with multiple commands using Windows batch file
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0 ... drive and path of argument 0 which is the batch file path.
choice /?
echo /?
endlocal /?
exit /?
goto /?
if /?
set /?
setlocal /?

insert a variable into a variable in batch

I'm trying to insert a variable into a variable, I've tried this, but it didn't work:
set gabriel-ctCODE=fmfg1
set /p user=Username:
set /p password=Password:
set /p ctCODE=ctCODE:
if %password%== %%user%-pass% set /a loginerrorlevel=%loginerrorlevel%+1
pause
if %ctCODE%== "%%user%-ctCODE%" set /a loginerrorlevel=%loginerrorlevel%+1
if not %loginerrorlevel%== 2 goto login.incorrect
goto :aftercommand
I would like to insert the "user" variable into this variable: %%user%-pass%
Could you help me please?
Here is your batch code rewritten for validating entered credential data:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "gabriel-ctCODE=fmfg1"
set "gabriel-pass=xxxyyy"
set "UserName="
set /P "UserName=User name: "
set "Password="
set /P "Password=Password: "
set "ctCODE="
set /P "ctCODE=ctCODE: "
call set "UserPass=%%%UserName%-pass%%"
call set "UserCode=%%%UserName%-ctCODE%%"
set "LoginErrorLevel=0"
if "!Password!" == "!UserPass!" set /A LoginErrorLevel+=1
if "!ctCODE!" == "!UserCode!" set /A LoginErrorLevel+=1
if not %LoginErrorLevel% == 2 goto LoginIncorrect
echo Entered credential data are valid for login.
goto EndBatch
:LoginIncorrect
echo Enter credential data not valid for login.
:EndBatch
endlocal
On set /P the user of the batch file has the freedom to enter nothing in which case the environment variable keeps its current value or is still not defined if not defined before. The batch code above makes sure that the 3 environment variables are not defined before prompting the user.
The batch file user has also the freedom to enter anything including critical characters for batch file execution like %, > <, ", etc. which is the reason for enclosing the variable=value assignments in double quotes as this results in interpreting the entered characters as literal characters and using delayed expansion on string comparisons.
Read the answers on Why is no string output with 'echo %var%' after using 'set var = text' on command line? and on Password system does not work for more details.
To get the values of the environment variables gabriel-ctCODE and gabriel-pass when the user enters gabriel (in any case) as user name, the command SET must be used with appropriate string and additionally the command CALL to expand the environment variable inside the variable string. Read for example answer on Pass environment variables to subshell CMD for details.
An arithmetic expression is everything after set /A which is interpreted by Windows command line interpreter completely different than usual.
For details on behavior of the commands SETLOCAL and ENDLOCAL read this answer.
For a basic understanding of the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?

Call batch within batch?

How do I call multiple batch files within a single batch? When I try it always goes to the same one or none at all and closes window.
#echo off
:MENU
title MENU0
Echo 1 - Select Menu 1
Echo 2 - Select Menu 2
Echo 0 - Exit
Echo.
SET /P choice=Type the number or letter of task you want, then press ENTER:
IF %choice%==1 GOTO 1
IF %choice%==2 GOTO 2
IF %choice%==0 EXIT
:1
call %userprofile%\desktop\\Menu1.bat
:2
call %userprofile%\desktop\Menu2.bat
There are several issues with provided batch code in question.
The first one is that after processing of the batch file called with command CALL finished, the processing of current batch file continues with the next command respectively line, except the called batch file contains itself the command EXIT without parameter /B as in this case the command processor terminates itself independent on calling hierarchy.
For details about CALL behavior see answers on:
How to call a batch file in the parent folder of current batch file?
In a Windows batch file, can you chain-execute something that is not another batch file?
The second issue is that folder path assigned to environment variable USERPROFILE could contain 1 or more spaces (default on Windows 2000/XP, possible on later Windows versions depending on user name). Therefore always enclose a string referencing USERPROFILE or USERNAME in double quotes.
The third and most difficult to handle issue is that the user of a batch file on prompt with set /P has the freedom to enter anything and not just what the writer of the batch file suggests.
For example
SET /P choice=Type the number or letter of task you want, then press ENTER:
IF %choice%==1 GOTO 1
results in an exit of batch processing caused by a syntax error if the batch user hits just RETURN or ENTER without entering anything at all and the environment variable choice is not already defined with a useful string because in this case the next line to process by command processor is:
IF ==1 GOTO 1
It is good practice to define the environment variable with a default value before set /P as this value is kept when the batch user just hits RETURN or ENTER.
A batch user has also the freedom on using set /P to enter anything including syntax critical characters like " or < or | or > and others by mistake or intentionally (for breaking batch processing by a syntax error).
Therefore it is in general better for menus in batch files to use the command choice (Microsoft article) because then the batch user can enter only what the writer of the batch file offers. But CHOICE is available only by default for Windows Server 2003 and later Windows. And there are different versions of choice (SS64 article with additional information) with a different set of options. So it depends on which Windows version(s) the batch file is designed for if CHOICE can be used at all.
It is also not good to name an environment variable or a label like a command although possible. Therefore choice is not a good name for an environment variable.
Here is a commented batch file with a code which avoids all those issues.
#echo off
:MainMenu
setlocal EnableDelayedExpansion
title MENU0
cls
echo 1 - Select Menu 1
echo 2 - Select Menu 2
echo 0 - Exit
echo.
rem Define 0 as default value in case of user just hits RETURN or ENTER.
set "UsersChoice=0"
set /P "UsersChoice=Type the number or letter of task you want, then press ENTER: "
rem Has the user really entered just one of the offered characters?
rem There must be nothing to process if the user has entered just 0
rem or 1 or 2. Otherwise the user's choice was either by mistake or
rem intentionally entered wrong. The string entered by the user is
rem referenced with delayed expansion to avoid an exit of batch
rem processing in case of user entered a syntax critical character.
for /F "tokens=1 delims=012" %%I in ("!UsersChoice!") do (
endlocal
goto MainMenu
)
rem Now it is safe to reference the variable value without usage of delayed
rem expansion as a syntax error caused by user input can't occur anymore.
rem The entered string does not contain any not expected character. But
rem it is possible that for example 11 was entered by mistake instead
rem of just 1. The entered string should have a length of 1 character.
if not "%UsersChoice:~1,1%" == "" (
endlocal
goto MainMenu
)
rem Exit this batch processing on user entered 0. Previous environment is
rem automatically restored by command processor by an implicit endlocal.
if "%UsersChoice%" == "0" exit /B
rem Restore previous environment as the called batch files are most
rem likely written for using standard command environment with delayed
rem expansion not enabled (exclamation mark interpreted different).
rem The current value of local environment variable must be passed
rem to previous environment for usage on GOTO command.
endlocal & goto Menu%UsersChoice%
:Menu1
call "%USERPROFILE%\Desktop\Menu1.bat"
goto MainMenu
:Menu2
call "%USERPROFILE%\Desktop\Menu2.bat"
goto MainMenu
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
cls /?
echo /?
endlocal /?
exit /?
for /?
goto /?
rem /?
set /?
setlocal /?
title /?
For meaning of & in line endlocal & goto Menu%UsersChoice% see answer on Single line with multiple commands using Windows batch file.
I tried your code and what I found was that when the input was 1 both :1 and :2 are executed but when the input is 2 only :2 is executed. To fix this you need to specify the end of :1 using Exit or another goto.
You might see that none the batches are being executed IF you do not put a pause in the end of your script. They would be executed but the result might just flash out of the screen.
Also I do not understand why have you used \\Menu1.batand not \Menu1.bat in
:1
call %userprofile%\desktop\\Menu1.bat
The final working code for me-
#echo off
:MENU
title MENU0
Echo 1 - Select Menu 1
Echo 2 - Select Menu 2
Echo 0 - Exit
Echo.
SET /P choice=Type the number or letter of task you want, then press ENTER:
IF %choice%==1 GOTO 1
IF %choice%==2 GOTO 2
IF %choice%==0 EXIT
:1
call yourpathhere\Menu1.bat
pause
GOTO cont
:2
call whatsoever\Menu2.bat
pause
GOTO cont
:cont
exit
That should fix your problem.
Hope I helped.
I may not be a pro, but I could help you!
I always add extra code on my games in order to avoid bugs, like this:
set /p letter=
if %letter% == 1 goto nocheck1
if %letter% == 2 goto nocheck2
if %letter% == 3 exit
:nocheck1
if %letter% == 1 goto saves
:nocheck2
if %letter% == 2 goto howtoplay
Maybe it could work on your problem!
I might have the code to do it:
#echo off
cls
:menu
cls
echo 1. Open Batch 1
echo 2. Open Batch 2
set /p test=Enter number here ----->
if %test% == 1 goto check1
if %test% == 2 goto check2
Edit the "Batch file name" text with your location of your batch file.
:check1
if %test% == 1 start C:\Users\%username%\Desktop\(batch file name).bat
:check2
if %test% == 2 start C:\Users\%username%\Desktop\(batch file name).bat
If there's still any errors with my code, let me know.
Hope this helps your problem!
Use cd to go to the location of batch file. For example:
rem myscript
echo calling batch file
cd demo\desktop\script
execute.bat
echo done
After the execution of that batch, control will return to the next line of your script.
Use "Start" instead of "Call" like so,
#echo off
:MENU
title MENU0
Echo 1 - Select Menu 1
Echo 2 - Select Menu 2
Echo 0 - Exit
Echo.
SET /P choice=Type the number or letter of task you want, then press ENTER:
IF %choice%==1 GOTO 1
IF %choice%==2 GOTO 2
IF %choice%==0 EXIT
:1
start %userprofile%\desktop\\Menu1.bat
:2
start %userprofile%\desktop\Menu2.bat
Try This:
#echo off
:MENU
title MENU0
Echo 1 - Select Menu 1
Echo 2 - Select Menu 2
Echo 0 - Exit
Echo.
SET /P choice=Type the number or letter of task you want, then press
Enter:
IF %choice%==1 GOTO 1
IF %choice%==2 GOTO 2
IF %choice%==0 EXIT
:1
cd users
cd %userprofile%
cd desktop
:: call Menu1.bat or use: start Menu1.bat
:: exit
:2
cd users
cd %userprofile%
cd desktop
:: call Menu2.bat or use: start Menu2.bat
:: exit
start "" C:\location\of\file\file.bat
This opens a new window, and as long as you have more commands to follow, the previous file that is calling the new one will still run along with this one.

set /a in If statement condition unable to work

Below are my simple calculator batch i trying to do, however on the set /a unable to do the job. What is the problem and my mistake?
#echo off
Title Calculator
:start
echo Press 1 for "+"
echo Press 2 for Exit
echo.
set /p input="Please choose your option: "
if %input%==1 (
echo.
set /p num1="Please enter first number: "
set /p num2="Please enter second number: "
set /a ans=%num1%+%num2%
echo Your answer is %ans%
pause
cls
goto start
)
if %input%==2 (
echo.
echo Thanks!
pause
exit
) else echo Invalid input!
pause
goto start
When i first run the batch is will return me the Missing operand. When i continue again the error disappear without giving me the answer, when the third time i continue, it return me the answer of the number that i wanted to add up.
For example:
1. 10+10 result is Missing operand
2. 1+1 result is empty
3. 2+2 result is 20 (which is the 2 number i enter at first time)
Please help what my error is. Thanks.
Here is your batch code with using delayed expansion and indents as wisely suggested by rojo:
#echo off
title Calculator
setlocal EnableExtensions EnableDelayedExpansion
:Begin
echo Press 1 for "+"
echo Press 2 for Exit
echo/
set "input="
set /P "input=Please choose your option: "
if "!input!"=="1" (
echo/
set /P "num1=Please enter first number: "
set /P "num2=Please enter second number: "
set /A ans=num1+num2
echo Your answer is !ans!
pause
cls
goto Begin
)
if "!input!"=="2" (
echo/
echo Thanks^^!
echo/
pause
exit /B
)
echo Invalid input^^!
echo/
pause
echo/
goto Begin
Variable input is always cleared before user is asked because otherwise the user could just hit key RETURN or ENTER to keep current value of variable input.
Delayed expansion is used on checking user input against 1 or 2 in case of user enters a character which would result in a syntax error on execution with not using delayed expansion. Better would be nevertheless the usage of command choice for first user prompt.
For an expression evaluated on runtime by using set /A the environment variables can be specified directly without being expanded at all. So instead of using
set /A ans=%num1%+%num2%
or
set /A ans=!num1!+!num2!
it is enough to write
set /A ans=num1+num2
because with parameter /A command set interprets num1 and num2 automatically as names of variables.
Delayed expansion is nevertheless needed to print the result value stored in variable ans because command processor expands otherwise %ans% by nothing respectively the value of previous run on parsing the entire block starting with ( and ending with ). This can be seen on running your batch file from within a command prompt window with first line changed to #echo on for debugging.
For more details run in a command prompt window set /? or help set and read the output help pages.
start is the name of a command. Therefore it is not good to use this word as name of a label although possible.
By the way: Always use set "variable=value" and never set variable="value" as this makes a big difference, see the answers on
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
How to set environment variables with spaces?

Using Variables to Change Directories

I am new to writing batch files. I want to create a batch file that will allow me to change 2 directories using variables. What I have below is what I have thus far. Any ideas?
#echo off
S:
cd AAA
set /p CLIENTCODE=CLIENTCODE?
cd %CLIENTCODE%
pause
set /p SCHEMANAME=SCHEMANAME?
cd %SCHEMANAME%
pause
Try following batch code:
#echo off
setlocal
set "ClientCode=AAA"
set "SchemaName=5H"
:UserPrompt
cls
set /P "ClientCode=Enter client code (default: %ClientCode%): "
set /P "SchemaName=Enter schema name (default: %SchemaName%): "
if not exist "S:\%ClientCode%\%ClientCode%%SchemaName%" goto InputError
cd /D "S:\%ClientCode%\%ClientCode%%SchemaName%"
endlocal
goto :EOF
:InputError
echo.
echo Client code "%ClientCode%" or schema name "%SchemaName%" is not valid.
set "InputAgain=Y"
set /P "InputAgain=Enter data again (Y/N)? "
if /I "%InputAgain%" == "Y" goto UserPrompt
if /I "%InputAgain%" == "YES" goto UserPrompt
endlocal
This batch file first defines defaults for client code and schema name making it possible for the user to simply hit key RETURN or ENTER when defaults are okay.
Next the window is cleared and the user is prompted for client code and schema name. The input of the user is not validated at all.
A very simple check is made if the appropriate directory (or file) exists.
The current directory is changed if a directory according to entered data exists.
If the directory does not exist, the user is asked if data input should be repeated in case of a typing mistake. The user can input Y or YES in any case to redo data input. Otherwise the batch script exits without changing the directory.
There is no real effort made on validating user input strings and verifying if the entered strings really lead to a directory and not a file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cls /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?

Resources