Verify 'X' number of digits have been inputted in batch script - windows

Writing a batch script. How can I verify '3' NUMERIC digits have been inputted by a user with the "/p" prompt?
Prompt to user:
SET /P SITEID=ENTER SITE # (i.e. 001 - MUST BE 3 DIGITS):
I need to verify 3 digits have been inputted, if good continue with script. If NOT good re-prompt user to message of my choosing.

#echo off
setlocal
set "Input="
:Prompt
set /p "Input=ENTER SITE # (i.e. 001 - MUST BE 3 DIGITS): "
if not defined Input goto Prompt
set "Input=%Input:"=%"
for /f "delims=0123456789" %%A in ("%Input%") do goto Prompt
for /f "tokens=1* delims=0" %%A in ("10%Input%") do set "Input=%%B"
if %Input%0 geq 10000 goto Prompt
set "Input=000%Input%"
set "Input=%Input:~-3%"
echo Success = %Input%
pause
endlocal
exit /b 0
Script Explanation:
Prompt for Input
Validate Input
Remove Poison Quotation Characters
Verify Input is only Numbers
Remove leading 0's for comparison
Verify Input is less than 1000
Add back leading 0's
Display Success
If any validation fails, the user is prompted again
Update:
Fix leading 0 removal
Add example of how to add back leading 0's

:loop
SET /P "SITEID=ENTER SITE # (i.e. 001 - MUST BE 3 DIGITS):"
echo("%SITEID:"= %"|findstr /rbe /c:"""[0-9][0-9][0-9]""" >nul || ( echo FAIL & goto loop )
It takes the %SITEID% variable, removes quotes if present and send the data into findstr to test against a regular expression (/r switch) : at the begining of data (/b switch) initial quote (from the echo command) three numeric characters, a closing quote (from the echo command) and end of string (/e switch). If the findstr does not found a match, errorlevel is set and the code after || is executed, printing a message to console an returning to the :loop label to ask again.

Related

Display Timer while a command is being executed in a batch file

Edit:
I shall thank Magoo for the detailed answer.
I edited my batch file according to Magoo's answer.
Here is the new code:
#echo off
mode 62,22
:Begin
choice /c 12345 /M "Insert a number (min. 1 - max. 5): "
set "CommandVar0=%errorlevel%"
choice /c 12345 /M "Please confirm the number you entered: "
set "CommandVarC=%errorlevel%"
if %CommandVarC% NEQ %CommandVar0% (
echo Insert a matching number between 1~5 for confirmation
goto Begin
)
if %CommandVar0% == 1 set /P CommandVar1=Insert ID:
if %CommandVar0% == 2 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID:
if %CommandVar0% == 3 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: & set /P CommandVar3=Insert ID:
if %CommandVar0% == 4 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: & set /P CommandVar3=Insert ID: & set /P CommandVar4=Insert ID:
if %CommandVar0% == 5 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID: & set /P CommandVar3=Insert ID: & set /P CommandVar4=Insert ID: & set /P CommandVar5=Insert ID:
:loop
start EXAMPLE.exe %CommandVar1%
if defined commandvar2 start EXAMPLE.exe %CommandVar2%
if defined commandvar3 start EXAMPLE.exe %CommandVar3%
if defined commandvar4 start EXAMPLE.exe %CommandVar4%
if defined commandvar5 start EXAMPLE.exe %CommandVar5%
rem wait 10 seconds
for /L %%y in (1,1,10) do (
timeout /t 1 > nul
tasklist /fi "imagename eq EXAMPLE.exe" |find ":" > nul
if NOT errorlevel 1 goto begin
)
taskkill /f /im EXAMPLE.exe
timeout /t 5
goto loop
The issue I'm having right now is that;
Due to my lack of knowledge, I don't know how to expand this command:
set "commandvar1="
set "commandvar2="
set /P CommandVar1=Insert ID:
if not defined commandvar1 goto begin
if "%CommandVar0%"=="2" (
set /P CommandVar2=Insert ID:
if not defined commandvar2 goto begin
)
e.g. to set "commandvar5=" etc. So instead I'm still using my complicated command which does the job for now.
How can I add the normal timer to this command?
for /L %%y in (1,1,10) do (
timeout /t 1 > nul
tasklist /fi "imagename eq EXAMPLE.exe" |find ":" > nul
if NOT errorlevel 1 goto begin
)
I want a timer to actually display the countdown of the command being executed like the usual timeout /t command if possible.
Addressing the core of the problem:
start EXAMPLE.exe %CommandVar1% & start EXAMPLE.exe %CommandVar2%
Will start two instances of example.exe passing the contents of commandvar? which may be response to "Insert ID:" or (rarely) nothing
Immediately thereafter, you are executing tasklist and looking for :.
If either the tasks have actually been established and is running, the tasklist output will NOT contain : so find will NOT find : and hence set errorlevel to 1
If the tasks have not been started or have both terminated, then the output of tasklist would be INFO: No tasks are running which match the specified criteria. which contains : and hence errorlevel will be set to 0.
Your next line says if **either** task is running (errorlevel 1), say "not found" and go to Begin otherwise (ie. neither task is running) then delay, taskkill the non-existent tasks, delay again and go back to Begin.
Another hidden problem is that when the routine returns to begin, if CommandVar2 has been set, then it will not be cleared, so it will remain set for the next input-cycle, regardless of the data input.
So we need to tackle the logic problems as well as the batch-syntax-specific problems.
Tip: Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign " or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier. If the syntax set var="value" is used, then the quotes become part of the value assigned.
First thing to tackle is the choose-and-check part. The value assigned to a variable by a set /p can be any string. That string may be the expected string or an unexpected string (obviously). An unexpected string may take many forms - it might contain spaces for instance, or unbalanced quotes, or % or parentheses or other strings or characters that have significance in the batch language. Also, responding with Enter to a set /p will leave the variable unchanged, not set it to nothing.
When the obvious parameter-check is executed via if %var1% == %var2% ..., then the values of the variables are substituted, and the comparison executed, so had the user input break me for instance, then batch would attempt to execute if break me == 2 ... and batch would see me where it expects to see a comparison-operator like ==.
The usual way to by-pass this problem is by "quoting both sides", ie. if "%var1%" == "%var2%" ... This is useful in the case that you may be processing some string containing spaces that is being returned from a command, but what happens if the user enters break " me ?
Consequently, the recommendation is to use the choice command to make 1-character choices (see choice /? from the prompt for documentation, or thousands of items on SO for examples)
Hence, your code should be
choice /c 12 /M "Insert a number (min. 1 - max. 2): "
set "CommandVar0=%errorlevel%"
choice /c 12 /M "Please confirm the number you entered: "
set "CommandVarC=%errorlevel%"
At this point, we are sure that commandvar? contains 1 or 2, so we can indeed use
if %CommandVarC% NEQ %CommandVar0% (
echo Insert a matching number between 1~2 for confirmation
goto Begin
)
Note: I've used the string-assignment syntax, even though the value assigned from %errorlevel% must be a pure-numeric string. It's also possible to use set /a var=%errorlevel% here. set /a assigns a value that we know is numeric (and can also do calculations) and needs no quotes.
There's no point in else... here -it serves to complicate matters. The code will simply continue to the next line if the goto is not executed.
if %CommandVarC% GTR 2 (echo Maximum number is 2.
goto Begin
) else (
is not required. We know that CommandVarC can only be 1 or 2.
if %CommandVar0% == 1 set /P CommandVar1=Insert ID:
if %CommandVar0% == 2 set /P CommandVar1=Insert ID: & set /P CommandVar2=Insert ID:
Well, this is overcomplicated, and doesn't quite do what is required. CommandVar1 is always required, and CommandVar2 will remain set if it has been set in the past.
Try:
set "commandvar1="
set "commandvar2="
set /P CommandVar1=Insert ID:
if not defined commandvar1 goto begin
if %CommandVar0% == 2 set /P CommandVar2=Insert ID:
Well, primitively. We know commandvar0 is a single digit, so we can use a simple ==. We also may or may not have received a response for commandvar2.
So
if "%CommandVar0%"=="2" (
set /P CommandVar2=Insert ID:
if not defined commandvar2 goto begin
)
may be more "according to Hoyle"
Summing up (before we tackle the next part), try using
choice /c 12 /M "Insert a number (min. 1 - max. 2): "
set "CommandVar0=%errorlevel%"
choice /c 12 /M "Please confirm the number you entered: "
set "CommandVarC=%errorlevel%"
if %CommandVarC% NEQ %CommandVar0% (
echo Insert a matching number between 1~2 for confirmation
goto Begin
)
set "commandvar1="
set "commandvar2="
set /P CommandVar1=Insert ID:
if not defined commandvar1 goto begin
if "%CommandVar0%"=="2" (
set /P CommandVar2=Insert ID:
if not defined commandvar2 goto begin
)
If we get past this point, I gather we should launch the executable, possibly twice, then wait for it to run, with a run-time limit of 10 seconds.
So,
start EXAMPLE.exe %CommandVar1%
rem only start a second instance if commandvar2 has been specified
if defined commandvar2 start EXAMPLE.exe %CommandVar2%
rem wait a sec...or 10
for /L %%y in (1,1,10) do (
timeout /t 1 >nul
tasklist /fi "imagename eq EXAMPLE.exe" |find ":" > nul
if NOT errorlevel 1 goto begin
)
rem kill tasks still running
taskkill /f /im EXAMPLE.exe
timeout /t 5
goto begin
for /L is explained at for /? from the prompt. Here, it counts %%y from 1 to 10 in steps of 1.
Each step delays 1 second (the >nul suppresses the countdown) then tests whether an executable is running. If NONE is running, then the tasklist will report a line containing : and errorlevel will be set to 0.
IF ERRORLEVEL n is TRUE if the runtime (ie. current) errorlevel is n or greater than n. IF ERRORLEVEL 0 is therefore always true. IF NOT ERRORLEVEL 1 is a test for errorlevel=0.
So, if there is no executable running, goto begin.
Once this test has been done 10 times, if an executable is running, then we exit the for /L loop and taskkill the remaining task(s) and back to the future...
--- To add Commandvars ---
The method is limited to 9 items without complications.
Change the 12 in the choice commands to 123456789 (or whatever your limit is).
add
for /L %%e in (1,1,9) do set "commandvar%%e="
in place of set "commandvar1=" set "commandvar2="
This will set all variablenames commandvar1..9 to nothing.
Then
for /L %%e in (1,1,9) do (
set /P CommandVar%%e="Insert ID for instance %%e: "
if not defined commandvar%%e (
if %%e==1 goto begin
goto startprocs
)
)
:startprocs
for /L %%e in (1,1,9) do if defined commandvar%%e call start "Instance %%e" u:\dummy.bat %%commandvar%%e%%
Note that the set/p has a quoted prompt-string. This allows the string to have a terminal space. It's possible to have that string "nude" but if your editor gets over-enthusiastic and removes terminal spaces, then you'd lose that one. It also serves to make the space obvious (stray spaces can cause havoc in batch)
Then input your data.
If the first entry is empty, back to the start. You could change that goto to an exit, which would terminate the cmd instance. or exit /b which would terminate this batch, but keep your cmd session open.
If any other entry is empty, it's the signal to start processing as we've finished our list.
The for /L for starting the processes has been changed a little. First, the start is immediately followed by a quoted string. This is the title which would appear in the process's window. It could be empty if you wish, but it should not be omitted in the general case. Start regards the first quoted string in the command as the window title to be used, so if it is omitted, a quoted string in the command may be eaten by start, used as a title and not passed to the process being started.
Then there's the call. This invokes a parser trick. Suppose %%e is 2. The command would be executed as call start "Instance 2" u:\dummy.bat %%commandvar%%e%% where %%commandvar%%e%% would be interpreted left-to-right as %commandvar2% as % is the "escape character" for %. Escaping a character is where we want to use a character without its special meaning. %%e is replaced by 2 first because it's an active metavariable (loop-control character or parameter-number). CALLin the resultant command start "Instance 2" u:\dummy.bat %commandvar2% then substitutes the current value of commandvar2 for the process.
=== Summary thought ===
With this new approach to have multiple commandvaar entries, there appears to be no reason for the nomination of a number of entries and then checking that number, so that entire section could be regarded as redundant.
If you remove that section, then there's no reason for the restriction to 9 items. You could set the limit to any number you like by replacing the 9 with 22, 35, 957 - whatever takes your fancy. The process will now start whenever you reply Enter to a prompt Insert ID for instance ??:
Parham.8, the error level is set after each command has been executed, if the next command succeeds, the error level will take 0 independent of the previous one. Use && to execute a command only if the previous command's error level is 0. Ex.
start EXAMPLE.exe %CommandVar1% && start EXAMPLE.exe %CommandVar2% && tasklist /fi "imagename eq EXAMPLE.exe" |find ":" > nul

Safe number comparison in Windows batch file

I know that when comparing stuff for equality in a batch file it's common to enclose both sides in quotes, like
IF "%myvar% NEQ "0"
But when comparing using "greater than" or "less than", this doesn't work because the operands would then be treated as strings with quotes around them. So you can instead just do
IF %myvar% GTR 20000
The caveat is that if the variable %myvar% isn't declared, it would be like doing
IF GTR 20000
which is a syntax error.
I came up with the following workaround:
IF 1%myvar% GTR 120000
which I'm hoping would result in IF 1 GTR 120000 if myvar is undefined, and it seems to work.
Is this a safe way to compare numbers and accounting for undeclared variables, or did I just open up a whole new can of caveats?
Let us assume the batch file contains:
#echo off
:PromptUser
rem Undefine environment variable MyVar in case of being already defined by chance.
set "MyVar="
rem Prompt user for a positive number in range 0 to 20000.
set /P "MyVar=Enter number [0,20000]: "
As I explained by my answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input? the user has the freedom to enter really anything including a string which could easily result in breaking batch file execution because of a syntax error or resulting in doing something the batch file is not written for.
1. User entered nothing
If the user hits just key RETURN or ENTER, the environment variable MyVar is not modified at all by command SET. It is easy to verify in this case with environment variable MyVar explicitly undefined before prompting the user if the user entered a string at all with:
if not defined MyVar goto PromptUser
Note: It is possible to use something different than set "MyVar=" like set "MyVar=1000" to define a default value which can be even output on prompt giving the user the possibility to just hit RETURN or ENTER to use the default value.
2. User entered a string with one or more "
The user could enter a string with one or more " intentionally or by mistake. For example pressing on a German keyboard key 2 on non-numeric keyboard with CapsLock currently enabled results in entering ", except German (IBM) is used on which CapsLock is by software only active for the letters. So if the user hits 2 and RETURN quickly or without looking on screen as many people do on typing on keyboard, a double quote character instead of 2 was entered by mistake by the user.
On MyVar holding a string with one or more " all %MyVar% or "%MyVar%" environment variable references are problematic because of %MyVar% is replaced by Windows command processor by user input string with one or more " which nearly always results in a syntax error or the batch file does something it was not designed for. See also How does the Windows Command Interpreter (CMD.EXE) parse scripts?
There are two solutions:
Enable delayed expansion and reference the environment variable using !MyVar! or "!MyVar!" as now the user input string does not affect anymore the command line executed by cmd.exe after parsing it.
Remove all " from user input string if this string should never contain a double quote character.
Character " is definitely invalid in a string which should be a number in range 0 to 20000 (decimal). For that reason two more lines can be used to prevent wrong processing of user input string caused by ".
set "MyVar=%MyVar:"=%"
if not defined MyVar goto PromptUser
The Windows command processor removes all doubles quotes already on parsing this line before replacing %MyVar:"=% with the resulting string. Therefore the finally executed command line set "MyVar=whatever was entered by the user" is safe on execution.
The example above with a by mistake entered " instead of 2 results in execution of set "MyVar=" which undefines the environment variable MyVar which is the reason why the IF condition as used before must be used again before further processing of the user input.
3. User entered non-valid character(s)
The user should enter a positive decimal number in range 0 to 20000. So any other character than 0123456789 in user input string is definitely invalid. Checking for any invalid character can be done for example with:
for /F delims^=0123456789^ eol^= %%I in ("%MyVar%") do goto PromptUser
The command FOR does not execute goto PromptUser if the entire string consists of just digits. In all other cases including a string starting with ; after zero or more digits results in execution of goto PromptUser because of input string contains a non-digit character.
4. User entered number with leading 0
Windows command processor interprets numbers with a leading 0 as octal numbers. But the number should be interpreted as decimal number even on user input it with one or more 0 at beginning. For that reason the leading zero(s) should be removed before further processing variable value.
for /F "tokens=* delims=0" %%I in ("%MyVar%") do set "MyVar=%%I"
if not defined MyVar set "MyVar=0"
FOR removes all 0 at beginning of string assigned to MyVar and assigns to loop variable I the remaining string which is assigned next to environment variable MyVar.
FOR runs in this case set "MyVar=%%I" even on user entered 0 or 000 with the result of executing set "MyVar=" which undefines environment variable MyVar in this special case. But 0 is a valid number and therefore the IF condition is necessary to redefine MyVar with string value 0 on user entered number 0 with one or more zeros.
5. User entered too large number
Now it is safe to use the command IF with operator GTR to validate if the user entered a too large number.
if %MyVar% GTR 20000 goto PromptUser
This last verification works even on user entering 82378488758723872198735897 which is larger than maximum positive 32 bit integer value 2147483647 because of the range overflow results in using 2147483647 on execution of this IF condition. See my answer on weird results with IF for details.
6. Possible solution 1
An entire batch file for safe evaluation of user input number in range 0 to 20000 for only decimal numbers is:
#echo off
set "MinValue=0"
set "MaxValue=20000"
:PromptUser
rem Undefine environment variable MyVar in case of being already defined by chance.
set "MyVar="
rem Prompt user for a positive number in range %MinValue% to %MaxValue%.
set /P "MyVar=Enter number [%MinValue%,%MaxValue%]: "
if not defined MyVar goto PromptUser
set "MyVar=%MyVar:"=%"
if not defined MyVar goto PromptUser
for /F delims^=0123456789^ eol^= %%I in ("%MyVar%") do goto PromptUser
for /F "tokens=* delims=0" %%I in ("%MyVar%") do set "MyVar=%%I"
if not defined MyVar set "MyVar=0"
if %MyVar% GTR %MaxValue% goto PromptUser
rem if %MyVar% LSS %MinValue% goto PromptUser
rem Output value of environment variable MyVar for visual verification.
set MyVar
pause
This solution gives the batch file writer also the possibility to output an error message informing the user why the input string was not accepted by the batch file.
The last IF condition with operator LSS is not needed if MinValue has value 0 which is the reason why it is commented out with command REM for this use case.
7. Possible solution 2
Here is one more safe solution which has the disadvantage that the user cannot enter a decimal number with one or more leading 0 being nevertheless interpreted decimal as expected usually by users.
#echo off
set "MinValue=0"
set "MaxValue=20000"
:PromptUser
rem Undefine environment variable MyVar in case of being already defined by chance.
set "MyVar="
rem Prompt user for a positive number in range %MinValue% to %MaxValue%.
set /P "MyVar=Enter number [%MinValue%,%MaxValue%]: "
if not defined MyVar goto PromptUser
setlocal EnableDelayedExpansion
set /A "Number=MyVar" 2>nul
if not "!Number!" == "!MyVar!" endlocal & goto PromptUser
endlocal
if %MyVar% GTR %MaxValue% goto PromptUser
if %MyVar% LSS %MinValue% goto PromptUser
rem Output value of environment variable MyVar for visual verification.
set MyVar
pause
This solution uses delayed environment variable expansion as written as first option on point 2 above.
An arithmetic expression is used to convert the user input string to a signed 32 bit integer interpreting the string as decimal, octal or hexadecimal number and back to a string assigned to environment variable Number on which decimal numeral system is used by Windows command processor. An error output on evaluation of the arithmetic expression because of an invalid user string is redirected to device NUL to suppress it.
Next is verified with using delayed expansion if the number string created by the arithmetic expression is not identical to the string entered by the user. This IF condition is true on invalid user input including number having leading zeros interpreted octal by cmd.exe or a number entered hexadecimal like 0x14 or 0xe3.
On passing the string comparison it is safe to compare value of MyVar with 20000 and 0 using the operators GTR and LSS.
Please read this answer for details about the commands SETLOCAL and ENDLOCAL because there is much more done on running setlocal EnableDelayedExpansion and endlocal than just enabling and disabling delayed environment variable expansion.
8. Possible solution 3
There is one more solution using less command lines if the value 0 is out of valid range, i.e. the number to enter by the user must be greater 0.
#echo off
set "MinValue=1"
set "MaxValue=20000"
:PromptUser
rem Undefine environment variable MyVar in case of being already defined by chance.
set "MyVar="
rem Prompt user for a positive number in range %MinValue% to %MaxValue%.
set /P "MyVar=Enter number [%MinValue%,%MaxValue%]: "
set /A MyVar+=0
if %MyVar% GTR %MaxValue% goto PromptUser
if %MyVar% LSS %MinValue% goto PromptUser
rem Output value of environment variable MyVar for visual verification.
set MyVar
pause
This code uses set /A MyVar+=0 to convert the user entered string to a 32-bit signed integer value and back to a string as suggested by aschipfl in his comment above.
The value of MyVar is 0 after command line with the arithmetic expression if the user did not input any string at all. It is also 0 if the user input string has as first character not one of these characters -+0123456789 like " or / or (.
A user input string starting with a digit, or - or + and next character is a digit, is converted to an integer value and back to a string value. The entered string can be a decimal number or an octal number or a hexadecimal number. Please take a look on my answer on Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files which explains in detail how Windows command processor converts a string to an integer value.
The disadvantage of this code is that a by mistake input string like 7"( instead of 728 caused by holding Shift on pressing the keys 2 and ( on a German keyboard is not detected by this code. MyVar has value 7 on user enters by mistake 7"(. Windows command processor interprets just the characters up to first not valid character for a decimal, hexadecimal or octal number as integer value and ignores the rest of the string.
The batch file using this code is safe against an unwanted exit of batch file processing because of a syntax error never occurs independent on what the user inputs. But a by mistake wrong input number is in some cases not detected by the code resulting in processing the batch file further with a number which the user did not want to use.
Answering the call to nitpick
Mofi has been requesting I write my own solution here, that is "shorter" as I pointed out to him the way he wrote his code using & instead of ( followed by a command then a carriage return and another command, or `( followed by a carriage return, followed by another command followed by a carriage return followed by another command) sets a precedent which makes this a hard task to agree on.
I also did not think this was the POINT of providing the answers perse, I mean I used to, but when changes are minor, and mainly fixing logic, or offering a minorly different solution, is that really a big difference? Does that really warrant being a separate answer?
That said, I don't see a better way without editing his response.. but this still leaves unresolved questions on what is being judged shorter.
Unfortunately as well, in discussing with Mofi he has edited his answer to one that can result in invalid choices.
While I have pointed this out, and I'm sure this was just a minor oversite on his part, I feel like not posting the code here has contributed to him actively deteriorating the quality of his question, which is always a possible outcome when nitpicking.
while Mofi was the driving force in that activity, I don't like the effect it's had on him as I was trying to avoid exactly this effect on my code by not getting into it, so I have decided to post the code comparison to bring some closure for them.
Please not, I will post his original code (the most recent one that did not use the erroneous method), and then refactored to how I would write it, and I will post my Original code, and then refactored to how I believe he would write it (may not be in that order but I will call out each)
So below is the result
Mofi Original:
This is hard to say if you should count every line, there are some instances where & is used to queue up commands and the IFS never use Parenthesis which I wouldn't generally do.
#echo off
set "MinValue=0"
set "MaxValue=20000"
:PromptUser
rem Undefine environment variable MyVar in case of being already defined by chance.
set "MyVar="
rem Prompt user for a positive number in range %MinValue% to %MaxValue%.
set /P "MyVar=Enter number [%MinValue%,%MaxValue%]: "
if not defined MyVar goto PromptUser
setlocal EnableDelayedExpansion
set /A "Number=MyVar" 2>nul
if not "!Number!" == "!MyVar!" endlocal & goto PromptUser
endlocal
if %MyVar% GTR %MaxValue% goto PromptUser
if %MyVar% LSS %MinValue% goto PromptUser
rem Output value of environment variable MyVar for visual verification.
set MyVar
pause
My Code Refactored to Mofi's Form
#ECHO OFF
SETLOCAL EnableDelayedExpansion
SET /A "_Min=-1","_Max=20000"
:Menu
CLS
SET "_Input="
REM Prompt user for a positive number in range %_Min% to %_Max%.
SET /P "_Input=Enter number [%_Min%,%_Max%]: "
SET /A "_Tmp=%_input%" && if /I "!_input!" EQU "!_Tmp!" if !_Input! GEQ %_Min% if !_Input! LEQ %_Max% SET _Input & pause & GOTO :EOF
GOTO :Menu
Mofi's Code Refactored
Mofi's above code Refactored to my more compacted form Where ( have the first command follow except when used on an IF statement, and ) follow the last command. This also makes the entire portion that really does the validation EASY to discern, it is only the portion within the :PromtUser function, not counting REM lines or blank lines this is 13 lines of code.
#(SETLOCAL
echo off
SET /A "MinValue=0","MaxValue=20000")
CALL :Main
( ENDLOCAL
EXIT /B )
:Main
CALL :PromptUser MyVar
REM Output value of environment variable MyVar for visual verIFication.
SET MyVar
PAUSE
GOTO :EOF
:PromptUser
SET "MyVar="
rem Prompt user for a positive number in range %MinValue% to %MaxValue%.
SET /P "MyVar=Enter number [%MinValue%,%MaxValue%]: "
IF NOT DEFINED MyVar GOTO :PromptUser
Setlocal EnableDelayedExpansion
SET /A "Number=MyVar" 2>nul
IF not "!Number!" == "!MyVar!" (
Endlocal
GOTO :PromptUser )
Endlocal
IF %MyVar% GTR %MaxValue% (
GOTO :PromptUser )
IF %MyVar% LSS %MinValue% (
GOTO :PromptUser )
GOTO :EOF
My Code in My Compact Form
To compare here is my code also in the same compact form I refactored Mofi's code to above. Again, only the lines inside of the function itself are "doing the heavy lifting" here and need compare. I did forget that when I worked on my code originally I was trying to match Mofi's form, and it allowed me an extra nicety in keeping my && ( in the following line or all as a single line. So I will post two varients
#(SETLOCAL ENABLEDELAYEDEXPANSION
ECHO OFF
SET /A "_Min=-1","_Max=20000" )
CALL :Main
( ENDLOCAL
EXIT /B )
:Main
CALL :Menu _input
REM Output value of environment variable _input for visual verIFication.
SET _input
PAUSE
GOTO :EOF
:Menu
CLS
SET "_input="
REM Prompt user for a positive number in range %_Min% to %_Max%. Store it in "_input"
SET /P "_Input=Enter number [%_Min%,%_Max%]: "
SET /A "_Tmp=%_input%" && (
IF /I "!_input!" EQU "!_Tmp!" IF !_Input! GEQ %_Min% IF !_Input! LEQ %_Max% GOTO :EOF )
GOTO :Menu
My Code in My Compact Form 2
#(SETLOCAL ENABLEDELAYEDEXPANSION
ECHO OFF
SET /A "_Min=-1","_Max=20000" )
CALL :Main
( ENDLOCAL
EXIT /B )
:Main
CALL :Menu
REM Output value of environment variable _input for visual verification.
SET _input
PAUSE
GOTO :EOF
:Menu
CLS
SET "_input="
REM Prompt user for a positive number in range %_Min% to %_Max%. Store it in "_input"
SET /P "_Input=Enter number [%_Min%,%_Max%]: "
SET /A "_Tmp=%_input%" || GOTO :Menu
IF /I "!_input!" EQU "!_Tmp!" (
IF !_Input! GEQ %_Min% (
IF !_Input! LEQ %_Max% (
GOTO :EOF ) ) )
GOTO :Menu

Batch file seems to be setting a variable to 2 for no reason

I'm making a simple batch script to figure out arrays in batch script.
The code:
#echo off
setlocal EnableDelayedExpansion
set inputCount=0
set outputCount=0
:input
cls
set /p !number%inputCount%!=Input %inputCount%:
set /a inputCount=%inputCount%+1
if %inputCount% geq 3 goto output
goto input
:output
cls
echo !number%outputCount%!
set /a outputCount=%outputCount%+1
if %outputCount% geq 3 goto exit
goto output
:exit
pause
echo exit
On line 4, I set outputCount to 0, I then don't change outputCount until line 16 where I add 1 to it.
I expected the output of line 16 to be outputCount=0+1=1 therefore making outputCount=1. However, when I run the code with echo on to see exactly what it's doing, the output for line 16 is outputCount=2+1=3 setting outputCount to 3.
It seems that the program is setting outputCount to 2 instead of 0 at some point before line 16 but I can't see why.
First, take a look on Debugging a batch file as this is a lesson you need to learn on coding a batch file.
Second, read the answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? which offers additional information to the help output on running in a command prompt window set /?.
It looks like you want to define the environment variables number0, number1 and number2 with a string assigned to them by user input.
The command to use to prompt a user for a string is either
set /P "variable=prompt text: "
or
set /P variable="prompt text: "
The first variant is in general recommended although most often not used by batch file coding newbies because of not knowing how to use the double quotes right on assigning a string to an environment variable. The second variant is specific for set /P also possible and in some very rare cases really needed, but in my point of view should be avoided to use because of the double quotes are interpreted different on using set without /P.
So let us look on your code with commenting out with rem four lines, appending one more line with set at end of the batch file and run that batch file from within a command prompt window:
rem #echo off
setlocal EnableDelayedExpansion
set inputCount=0
set outputCount=0
:input
rem cls
set /p !number%inputCount%!=Input %inputCount%:
set /a inputCount=%inputCount%+1
if %inputCount% geq 3 goto output
goto input
:output
rem cls
echo !number%outputCount%!
set /a outputCount=%outputCount%+1
if %outputCount% geq 3 goto exit
goto output
:exit
rem pause
echo exit
set number
Output is at end just a line with NUMBER_OF_PROCESSORS=2. There are no environment variables number0, number1, number2 which would be also output by set number. And the command line echo !number%outputCount%! in file results three times in the information that ECHO is OFF.
The reason can be seen on looking on the output command lines really executed after preprocessing each line by Windows command interpreter.
set /p !number%inputCount%!=Input %inputCount%:
The string entered by the user, if not just RETURN or ENTER was hit by the user on prompt, should be assigned to the environment variables of which name are stored in the environment variables number0, number1 and number2. But the environment variables number0, number1 and number2 are never defined by your batch file as your intention is to store the input strings into the variables with name number0, number1 and number2. So this command line is finally on execution:
set /p =Input 0:
set /p =Input 1:
set /p =Input 2:
Those command lines would result in an exit of batch processing because of a syntax error, but this does not occur here because of usage of delayed expansion as it can be seen in the console window.
The solution is a batch code as follows:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "Index=0"
:Input
cls
set /A Index+=1
set /P "Number%Index%=Input %Index%: "
if not %Index% == 3 goto Input
cls
set "Index=0"
:Output
set /A Index+=1
if defined Number%Index% echo Number%Index%=!Number%Index%!
if not %Index% == 3 goto Output
endlocal
The output of this batch file on entering on first prompt Hello!, on second prompt nothing and on third prompt Bye! is:
Number1=Hello!
Number3=Bye!
Okay, we have not entered a number as we have the freedom to type anything from nothing to bad strings like Double quote " or | or < or > are bad inputs on user prompt on being prompted for an input. But the batch file works as expected now.
Further please note that the string after set /A is an arithmetic expression which is parsed completely different to any other string on a command line. For examples the current values of environment variables can be referenced by using just the variable name without surrounding percent signs or exclamation marks. That make it possible to use variables in arithmetic expression within an IF or FOR command block without usage of delayed expansion. The help output on running set /? in a command prompt window explains this different parsing behavior quite good as well as which operators can be used like += in the arithmetic expression.
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 /?
rem /?
set /?
setlocal /?
Some more hints:
Don't use just exit in a batch file, use exit /B or goto :EOF, see Where does GOTO :EOF return to?
After verification that the user entered anything at all and the entered string is really a number (decimal, octal or hexadecimal), make sure to process the number right according to your and the users' expectations. What I mean here is demonstrated with:
#echo off
set "Number=020"
set /A Number+=1
echo Result=%Number%
pause
What do you expect as result, 21 or the real output result 17?
A number string starting with 0 is interpreted as octal number. A number string starting with 0x or 0X is interpreted as hexadecimal number. Change 020 to 008 and the result is 1. Why? 008 is invalid for an octal number and therefore replaced by 0 which is incremented by one.

Prevent batch script from terminating upon invalid character input

I always have this issue when writing batch scripts. Whenever I have the script prompt the user to set a variable, if a semicolon (that's just one example) is inputted, the script will close. Is there a way to prevent it from doing so?
Example:
#echo off
:1
cls
echo Please enter your ID:
set /P id=
if /i %id%==119 goto Tom
if /i %id%==204 goto Brittany
if /i %id%==12 goto Shannon
if /i %id%==64 goto Jack
goto 1
:Tom
cls
echo Tom, you have to mow the lawn.
pause>nul
exit
:Brittany
cls
echo Brittany, you have to fold the laundry.
pause>nul
exit
:Shannon
cls
echo Shannon, you have to feed the dog.
pause>nul
exit
:Jack
cls
echo Jack, you have to replace the radio's capacitors.
pause>nul
exit
What I would see running that script:
C:\>myscript.bat
Please enter your ID:
asjfash;dfjlas;ldf
asjfash;dfjlas;ldf==i was unexpected at this time.
and the script closes.
Thanks!
Read Syntax : Escape Characters, Delimiters and Quotes:
Delimiters
Delimiters separate one parameter from the next - they split the
command line up into words.
Parameters are most often separated by spaces, but any of the
following are also valid delimiters:
Comma (,)
Semicolon (;)
Equals (=)
Space ()
Tab (   )
If a user inputs some string containing any of above listed separators (like set "id=1 19" then %id% contains a space), then
if /i %id%==119 goto Tom
results to
if /i 1 19==119 goto Tom
↑ this space causes error 19==119 was unexpected at this time
Definitely, you need to escape delimiters and all other cmd-poisonous characters as follows:
#echo off
:1
cls
echo Please enter your ID:
set /P id=
if /i "%id%"=="119" goto Tom
if /i "%id%"=="204" goto Brittany
if /i "%id%"=="12" goto Shannon
if /i "%id%"=="64" goto Jack
goto 1
rem script continues here
FYI, Redirection article lists other cmd-poisonous characters which need to be escaped as their unescaped occurrence in a batch script has following meaning:
&  - Single Ampersand: used as a command separator
&& - Double Ampersand: conditional command separator (like if errorlevel 0)
|| - Double Pipe (Vertical Line): conditional command separator (like if errorlevel 1)
|  - Single Pipe: redirects the std.output of one command into the std.input of another
>  - Single Greater Than: redirects output to either a file or file like device
>> - Double Greater than: output will be added to the very end of the file
<  - Less Than: redirect the contents of a file to the std.input of a command

batch file IF vs ECHO giving different results

I have this weird problem happening
I am downloading a a file using a wget, then set a var as first line of file, then comparing to string to verify the file. Weird thing is var is set as expected, echo works fien but when I use if to compare, var blows up. Look at example below:
set /p first_line=< c:\data.dsv
echo %first_line%
if %first_line% == SomefirstLine GOTO Success
When batch runs, echo gives correct var value, but in if it give first 3 lines, why is this weird thing happening?
The reason is probably the line termination in the downloaded file. If lines end with 0x0A (linefeed) without a 0x0D (carriage return), the set /p will read until the first 0x0D, end of file or max length is retrieved.
echo command will output until the first 0x0A, but the variable contents are the three "lines", and it can be verified using set first_line to see the real content of the variable.
You can use
set "first_line="
for /f "delims=" %%a in (c:\data.dsv) do set "first_line=%%a" & goto done
:done
Or if you prefer to read the file with the set /p method, then do that same processing on the retrieved variable to extract the required value
set /p first_line=< c:\data.dsv
set "first_first_line="
for /f "delims=" %%a in ("%first_line%"
) do if not defined first_first_line set "first_fisrt_line=%%a"
EDITED - It seems the OS versions affects the way it works.
The second proposed code was tested in a machine with XP and it worked, but in windows 7 it does not work. Once tested, the for command, instead of splitting the string on the 0x0A character, removes the 0x0A and the three lines are joined into one that is assigned to the variable. So, only the first option (with just the for loop) works on both versions.
Option 3 - To avoid reading the full file into memory, the output of the set command can be parsed to retrieve the real first line.
#echo off
:: get data
set /p "first_line="<c:\data.dsv
:: show data
echo(data retrieved with set /p
echo(----------------------------------------------------
echo(%first_line%
echo(----------------------------------------------------
set first_line
echo(----------------------------------------------------
echo(
:: get data 2
for /f "tokens=1,* delims==" %%a in ('set first_line^|find "first_line="') do set "first_line=%%b"
:: show data
echo(data retrieved with for
echo(----------------------------------------------------
echo(%first_line%
echo(----------------------------------------------------
set first_line
echo(----------------------------------------------------
:: test data
set "SomeFirstLine=...."
if "%first_line%"=="SomeFirstLine" GOTO Success
Note the double quotes in the if compare - they protect it from spaces and & characters.
set /p first_line=< c:\data.dsv
echo %first_line%
if "%first_line%" == "SomefirstLine" GOTO Success

Resources