CMD - language query task - windows

I would like to make a batch, which query the OS's language and after it does commands depending the result.
My code is:
#echo off
reg query "hklm\system\controlset001\control\nls\language" /v Installlanguage
if %ERRORLEVEL% EQU 0409 GOTO ENGLISH
GOTO GERMANY
:ENGLISH
echo English
PAUSE
:GERMANY
echo Germany
PAUSE
I know if the req query result is 0409--> English, 0407--> Germany.
I try with:
reg query "hklm\system\controlset001\control\nls\language" /v Installlanguage
if %ERRORLEVEL% EQU 0409 (GOTO ENGLISH)
else %ERRORLEVEL% EQU 0409 (GOTO GERMANY)
But didn't work. Can somebody help me?
I don't know if there is a problem with the if function. Or that cmd cannot read the received value.

well, reg returns an %errorlevel% of zero, if successful or one, if unsuccessful (typo, key or value non-existent).
You need to parse the output with a for /f loop to get the desired number:
for /f "tokens=3" %%a in ('reg query "hklm\system\controlset001\control\nls\language" /v Installlanguage') do set "lang=%%a"
if "%lang%" == "0407" goto :German
if "%lang%" == "0409" goto :English
echo There is no label for %lang%
goto :eof
:ENGLISH
echo English
PAUSE
goto :eof
:GERMANY
echo Germany
PAUSE
goto :eof
You have to force if to compare strings instead of numbers because numbers starting with a zero are treated as octal, which means 0409 is an invalid octal number and will lead to a script-breaking error if treated as a number.
You have to terminate your main code and subroutines with a goto :eof to prevent the parser to "fall through" the following subroutine.

Related

Using Findstr with specific range or other method

I only want to find specific lines in his text file, so i figure that using range would be a good idea. But i can seem to find any tutorial online. please help..
An example of the text file
XXX scan report for 192.0.0.0
exampleexampleexampleexampleexample
OS: windows 8
exampleexampleexampleexample
exampleexampleexampleexample
PORT STATE SERVICE VERSION
21/tcp close ftp
80/tcp open http Microsoft ISS
exampleexampleexampleexample
exampleexampleexampleexample
XXX scan report for 192.0.0.1
exampleexampleexampleexampleexample
exampleexampleexampleexample
exampleexampleexampleexample
PORT STATE SERVICE VERSION
21/tcp close ftp
80/tcp open http Microsoft ISS
exampleexampleexampleexample
exampleexampleexampleexample
I wanted to get IP address, OS Details and Port status into a spreadsheet.
My code:
#echo off
set file=C:\Users\1.txt
set match=report for
set match1=OS
findstr /c:"%match%" %file%
findstr /c:"%match1%" %file%
findstr /c:"tcp " /c:"udp " %file%
for /f "tokens=1-5" %%a in ('findstr /c:"%match%" %file%') do (
echo "IP Address:","%%e" >> report1.csv
for /f "tokens=1,2 delims=:*" %%a in ('findstr /c:"%match1%" %file%') do
(
echo "Operating System: ","%%b" >> report1.csv
echo "PORT","STATE","SERVICE","VERSION" >> report1.csv
for /f "tokens=1-4 delims=: " %%a in ('findstr /c:"tcp " /c:"udp "
%file%') do (
echo "%%a","%%b","%%c","%%d" >> report1.csv
)
)
)
There is a big problem with this code and it is in the for loop.
The code will get the first ip then will proceed to get the os details, but not ever ip have the os details, so the os details will be placed in the wrong ip.
Another problem with the code is that it will list all os and port details under one ip address. And the next ip address will also be the same, it will have all the os and port details as well.
Please do help me to solve this problem. Or is there any other method like call?
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q43335765.txt"
SET "outfile=%destdir%\outfile.txt"
>"%outfile%" ECHO IP,OS,PORT,STATUS,SERVICE,VERSION
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
CALL :process %%a
)
GOTO :EOF
:process
ECHO %*|FIND "scan report for " >NUL
IF NOT ERRORLEVEL 1 GOTO newip
IF "%~1"=="OS:" SET "$os=%*"&GOTO :eof
ECHO %~1|FIND "/">NUL
IF ERRORLEVEL 1 GOTO :EOF
FOR /f "tokens=1,2,3*" %%p IN (
"%*") DO >>"%outfile%" ECHO %$ip%,%$os:*: =%,%%p,%%q,%%r,%%s
GOTO :eof
:newip
IF "%~2" neq "" shift&GOTO newip
SET "$ip=%~1"
SET "$os=: "
GOTO :eof
You would need to change the settings of sourcedir and destdir to suit your circumstances.
I used a file named q43335765.txt containing your data for my testing.
Produces the file defined as %outfile%
Having established the filenames, put the header line in the output file and process each line of the file through :process
In :process, detect the key string indicating a ne data item. If found, go to :newip which simply shuffles the data line along until only the last entry remains and assign this last entry to $ip. Set $ip to :Space + any special string you want to represent "not found" (like unknown for instance)
If the line doesn't contain the keystring, see whether the first token is OS:, and set $os to the entire original line if it is.
Otherwise, lookk for a / in the first token. If it's not there, abandon processing this line, otherwise simply tokenise the line, selecting the first to thid and rest and output using the saved ip, the saved os, except for the part before the first :Space and the four data line entries, all separated by commas.
Revision to cater for | in data - replace with /
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q43335765.txt"
SET "outfile=%destdir%\outfile.txt"
>"%outfile%" ECHO IP,OS,PORT,STATUS,SERVICE,VERSION
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
SET "line=%%a"
CALL :preprocess
)
GOTO :EOF
:preprocess
SET "line=%Line:|=/%"
CALL :process %line%
GOTO :eof
:process
ECHO %*|FIND "scan report for " >NUL
IF NOT ERRORLEVEL 1 GOTO newip
IF "%~1"=="OS:" SET "$os=%*"&GOTO :eof
ECHO %~1|FIND "/">NUL
IF ERRORLEVEL 1 GOTO :EOF
FOR /f "tokens=1,2,3*" %%p IN (
"%*") DO >>"%outfile%" ECHO %$ip%,%$os:*: =%,%%p,%%q,%%r,%%s
GOTO :eof
:newip
IF "%~2" neq "" shift&GOTO newip
SET "$ip=%~1"
SET "$os=: "
GOTO :eof
Shows the need to provide a representative data sample...
With characters that have special meaning like |, assign to a variable and call a preprocessor to convert all | to / (or whatever else is desired) and then call the process with the result.
Formula: set "var=%somevar:string1=string2%"
will assign to var the value of somevar with all occurrences of string1 replaced by string2. The enclosing quotes in a set command ensure that any stray trailing spaces on the line are not included in the value assigned.
The flaw in your logic is that each time you execute findstr, it starts back at line 1 of your text file. If you're working with multi-line records, you have to build your line of output with in one pass of the record. I suggest a for /F loop and testing tokens is better suited to this than findstr. Here's a suggestion:
#echo off
setlocal
set "file="C:\Users\1.txt"
>"report1.csv" (
echo "IP Address","Operating System","port 21","port 80"
for /F "usebackq tokens=1-3,5" %%I in ("%file%") do (
rem // check if line begins a record
if /i "%%~J"=="scan" if /i "%%~K"=="report" (
set "IP=%%~L"
set "OS="
)
rem // check if line contains OS
if /i "%%~I"=="OS:" set OS="%%~J %%~K"
rem // check if line contains port 21
if /i "%%~I"=="21/tcp" set "state21=%%~J"
rem // port 80 indicates end of needed info in record
setlocal enabledelayedexpansion
if /i "%%~I"=="80/tcp" echo(!IP!,!OS!,!state21!,%%~J
endlocal
)
)

How to limit a batch variable's length

Is it any way to limit the length of a batch variable? I mean, if it is possible to program a variable that only admits between 0 and x characters? So, for an instance, if I entered 123456 and the max length was 4 it wouldn't proceed to continue. I hope you can understand my question.
Thanks in advance.
Demonstration batch code according to suggestions of aschipfl and rojo:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
:UserPrompt
cls
set "UserInput="
set /P "UserInput=Enter string with a length between 1 and 4: "
if not defined UserInput goto UserPrompt
if not "!UserInput:~4!" == "" goto UserPrompt
echo/
echo String entered: !UserInput!
echo/
endlocal
pause
!UserInput:~4! is replaced by command processor on execution of the batch file by the string from user input starting with fifth character. First character of a string value has index value 0 which is reason for number 4 for fifth character. This string is empty if user entered a string not longer than 4 characters, otherwise this substring is not empty resulting in user must input again a string.
Delayed expansion is used to avoid an exit of batch processing caused by a syntax error if the user enters a string containing an odd number of double quotes.
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 /?
if /?
pause /?
set /?
setlocal /?
If you mean "limit the length of a batch variable when it is read via SET /P command", then you may use the ReadLine subroutine described at this post, that emulates SET /P command using pure Batch file commands, and just insert the maximum length restriction.
#echo off
setlocal
call :ReadNChars string4="Enter 4 characters maximum: " 4
echo String read: "%string4%"
goto :EOF
:ReadNChars var="prompt" maxLen
rem Read a line emulating SET /P command
rem Antonio Perez Ayala
rem Initialize variables
setlocal EnableDelayedExpansion
echo > _
for /F %%a in ('copy /Z _ NUL') do set "CR=%%a"
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
rem Show the prompt and start reading
set /P "=%~2" < NUL
set "input="
set i=0
:nextKey
set "key="
for /F "delims=" %%a in ('xcopy /W _ _ 2^>NUL') do if not defined key set "key=%%a"
rem If key is CR: terminate input
if "!key:~-1!" equ "!CR!" goto endRead
rem If key is BS: delete last char, if any
set "key=!key:~-1!"
if "!key!" equ "!BS!" (
if %i% gtr 0 (
set /P "=!BS! !BS!" < NUL
set "input=%input:~0,-1%"
set /A i-=1
)
goto nextKey
)
rem Insert here any filter on the key
if %i% equ %3 goto nextKey
rem Else: show and accept the key
set /P "=.!BS!%key%" < NUL
set "input=%input%%key%"
set /A i+=1
goto nextKey
:endRead
echo/
del _
endlocal & set "%~1=%input%"
exit /B
However, if you want to limit the length of a Batch variable in other cases, like SET /A or plain SET commands, then there is no way to do that. Of course, you may execute such commands and then cut the variable value to the maximum length, but that process is an entirely different thing.

'if errorlevel' statement when in 'for findstr' loop

I have been unsuccessful getting the following to work. Everything works until I try to get the results of the 'findstr' in the 'for' loop. Maybe there is a better way of doing this: look for %subnet% in the masters.csv file. If it finds it, set the MSS variable to the resulting value from the 'for'. If it does not find a value, it will assign a static value (orphan). Thanks in advance for any help!!
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip% > ipaddress.txt
pause
for /F "tokens=1-3 delims=." %%a in ("%ip%") do set FirstThreeOctets=%%a.%%b.%%c
#REM echo First three: %FirstThreeOctets%
#echo off
setlocal
set subnet=%FirstThreeOctets%
echo %subnet%
for /f "tokens=2 delims=," %%A in ('findstr /r "^%subnet%," "\\server\APPS\appname\updates\masters.csv"') do goto OrphanCheck
#REM if errorlevel ==1 goto Orphan do set MSS=%%A
#REM echo %MSS%
#REM goto 64installcheck
:OrphanCheck
if errorlevel==1 goto Orphan
Goto NoOrphan
:NoOrphan
set MSS=%%A
Goto 64installcheck
:Orphan
set MSS=ORPHAN
echo %MSS%
pause
When you run
for /f "tokens=2 delims=," %%A in (
'findstr /r "^%subnet%," "\\server\APPS\appname\updates\masters.csv"'
) do goto OrphanCheck
two things can happen.
If findstr does not find the string, code in for loop is not executed and the next line is reached, but this line does not have access to the errorlevel generated by the findstr, it sees the errorlevel (?) of the for command.
If findstr finds the string, the goto is executed but the same scenario happens.
When the line that checks the error level is reached, another problem raises
if errorlevel==1
is a valid construct, but it does not do what it seams. It is testing if the string errorlevel is equal to the string 1. The correct sintax should be
if errorlevel 1 ....
or
if %errorlevel%==1
but as indicated, when the line is reached the errorlevel will not reflect the error of the findstr command.
And three lines later the next error.
set MSS=%%A
Once the for command has ended, its replaceable parameter does not have any value.
For a simplified version of your code
for /f "tokens=3-6 delims=.: " %%a in ('ipconfig ^| find "IPv4"') do (
set "ip=%%a.%%b.%%c.%%d"
set "subnet=%%a.%%b.%%c"
)
>"ipaddress.txt" echo %ip%
for /f "tokens=2 delims=," %%a in (
'findstr /b /c:"%subnet%," "\\server\APPS\appname\updates\masters.csv"'
) do (
set "MSS=%%a"
goto 64installcheck
)
set "MSS=ORPHAN"
echo %MSS%
pause

How do I display integers in hexadecimal, from a batch file?

echo The error level is: %ERRORLEVEL%
Produces
>The error level is: 15
What I would like:
>The error level is: F
do I need to do conversions or is there a way to display numbers differently?
Any help in the right direction is appreciated, thanks.
It was a long time ago, I was very bored.
cmdcalc.cmd
#echo off
if not defined trace set trace=rem
%trace% on
SetLocal
if "%1"=="/?" (
call :help %0
goto :eof
)
Set MinInBase=
if /i "%2" EQU "Bin" call :DoBin %1
if /i "%2" EQU "Hex" call :DoHex %1
If not defined BinStr call :DoDec %1
EndLocal & set RET=%RET%
goto :eof
:DoBin
Set MinInBase=2
Set ShiftBy=1
Set StartSyn=0b
call :DoCalc %1
goto :eof
:DoHex
Set MinInBase=16
Set ShiftBy=4
Set StartSyn=0x
call :DoCalc %1
goto :eof
:DoDec
if {%1} EQU {} goto :eof
set /a BinStr=%1
set RET=%BinStr%
echo %RET%
goto :eof
:DoCalc
Set BinStr=
SET /A A=%1
%Trace% %A%
:StartSplit
SET /A B="A>>%ShiftBy%"
%Trace% %B%
SET /A C="B<<%ShiftBy%"
%Trace% %C%
SET /A C=A-C
%Trace% %C%
call :StringIt %C%
If %B% LSS %MinInBase% goto :EndSplit
set A=%B%
goto :StartSplit
:EndSplit
call :StringIt %B%
set RET=%StartSyn%%BinStr%
Echo %RET%
EndLocal & set RET=%RET%
goto :eof
:StringIt
set Bin=0123456789ABCDEF
FOR /F "tokens=*" %%A in ('echo "%%BIN:~%1,1%%"') do set RET=%%A
set ret=%ret:"=%
Set BinStr=%Ret%%BinStr%
goto :eof
:help
echo %1 syntax:
echo.
echo %1 Calculation [Hex^|Bin]
echo.
echo eg %1 12*2 Hex
echo.
echo gives 0x18.
goto :eof
According to the external resource Windows Environment Variables, there is an undocumented built-in read-only variable =ExitCode which returns the current exit code in hexadecimal format. To ensure the ErrorLevel value equals the exit code, use cmd /C exit %ErrorLevel%.
So if you are using this line code...:
cmd /C exit %ErrorLevel%
echo The error level is: %=ExitCode%
...you will receive this (supposing the ErrorLevel is 15):
The error level is: 0000000F
To get rid of the leading zeros, use this...:
cmd /C exit %ErrorLevel%
for /F "tokens=* delims=0" %%Z in ("%=ExitCode%") do set "HEXCODE=%%Z"
if not defined HEXCODE set "HEXCODE=0"
echo The error level is: %HEXCODE%
...to get this:
The error level is: F
Just write it in vbscript instead of batch
put the vbscript statement below into a file.
WScript.Echo Hex( WScript.Arguments(0) )
then to run it, simple type this on the command line ( in a batch script, use a for loop to capture the value if required )
C:\workspace> cscript //nologo hex.vbs 15
F
There is no need to install anything. vbscript comes by default in most windows systems.
perl -e"printf qq{The errorlevel is: %X\n}, $ENV{ERRORLEVEL}"
Requires Perl to be installed, of course, but that's easy to do.

Batch File input validation - Make sure user entered an integer

I'm experimenting with a Windows batch file to perform a simple operation which requires the user to enter a non-negative integer. I'm using simple batch-file techniques to get user input:
#ECHO OFF
SET /P UserInput=Please Enter a Number:
The user can enter any text they want here, so I would like to add some routine to make sure what the user entered was a valid number. That is... they entered at least one character, and every character is a number from 0 to 9. I'd like something I can feed the UserInput into. At the end of the routine would be like an if/then that would run different statements based on whether or not it was actually a valid number.
I've experimented with loops and substrings and such, but my knowledge and understanding is still slim... so any help would be appreciated.
I could build an executable, and I know there are nicer ways to do things than batch files, but at least for this task I'm trying to keep it simple by using a batch file.
You're probably not doing this in a DOS batch file. Or at least, support for set /p is unheard of for me in DOS :-)
You could use substrings. In fact I have written a parser for a specific regular language that way once, but it's cumbersome. The easiest way would probably be to assign the contents of %userinput% to another variable, using set /a. If the result comes out as 0 you need to check whether the input itself was 0, otherwise you can conclude it was a non-number:
#echo off
setlocal enableextensions enabledelayedexpansion
set /p UserInput=Enter a number:
set /a Test=UserInput
if !Test! EQU 0 (
if !UserInput! EQU 0 (
echo Number
) else (
echo Not a number
)
) else (
echo Number
)
However, this works only for numbers in the range of Int32. If you just care for any number (possibly floating-point as well) then you need to resort to the loop-based approach of dissecting it.
NOTE: Updated to solve the space issues. However, there is still a problem lurking: Entering 123/5 yields "number", since set /a can evaluate this ...
Thanks all. I was trying to make it harder for myself looking at loops and string manipulation. I used your tips on math evaluation and comparison. Here's what I finally came up with as my concept script:
:Top
#ECHO OFF
ECHO.
ECHO ---------------------------------------
SET /P UserInput=Please Enter a Number:
ECHO.
ECHO UserInput = %UserInput%
ECHO.
SET /A Evaluated=UserInput
ECHO Math-Evaluated UserInput = %Evaluated%
if %Evaluated% EQU %UserInput% (
ECHO Integer
IF %UserInput% GTR 0 ( ECHO Positive )
IF %UserInput% LSS 0 ( ECHO Negative )
IF %UserInput% EQU 0 ( ECHO Zero )
REM - Other Comparison operators for numbers
REM - LEQ - Less Than or Equal To
REM - GEQ - Greater Than or Equal To
REM - NEQ - Not Equal To
) ELSE (
REM - Non-numbers and decimal numbers get kicked out here
ECHO Non-Integer
)
GOTO Top
This method catches all numbers and can detect whether it's positive, negative, or zero. Any decimal or string will be detected as non-integers. The only edge case I've found is a string with spaces. For example, the text "Number 1" will cause the script to crash/close when the user input is evaluated as math. But in my situation, this is fine. I don't want my script to go on with invalid input.
You can also use a quite simple trick:
echo %userinput%|findstr /r /c:"^[0-9][0-9]*$" >nul
if errorlevel 1 (echo not a number) else (echo number)
This uses findstr's regular expression matching capabilities. They aren't very impressive but useful at times.
This is the same idea as that of Johannes..
SET /A sets a numeric value. If the input is not a number, it changes it to 0.
That's what you can exploit here to do your check.
#ECHO OFF
SET /P UserInput=Please Enter a Number:
IF %UserInput% EQU 0 GOTO E_INVALIDINPUT
SET /A UserInputVal="%UserInput%"*1
IF %UserInputVal% GTR 0 ECHO UserInput "%UserInputVal%" is a number
IF %UserInputVal% EQU 0 ECHO UserInput "%UserInputVal%" is not a number
GOTO EOF
:E_INVALIDINPUT
ECHO Invalid user input
:EOF
As an alternative, you could always create a little javascript file and call it from your batchfile. With parseInt() you could force the input to be an integer, or you could roll your own function to test the input.
Writing the javascript is just as fast as the batchfile, but it's much more powerful. No IDE or compiler required; notepad will do. Runs on every windows box, just like your batchfiles. So why not make use of it?
You can even mix batchfiles and javascript. Example:
contents of sleep.js:
var SleepSecs=WScript.Arguments.Item(0);
WScript.Sleep(SleepSecs*1000)
contents of sleep.cmd:
cscript /nologo sleep.js %1
You can now call this from a batchfile to make your script sleep for 10 seconds. Something like that is difficult to do with just a plain batchfile.
sleep 10
As pointed out by ghostdog74, the answers posted by Joey Mar 26 '09 (score 10) and Wouter van Nifterick Mar 26 '09 (score 5) don't work.
The answer posted by Joey Mar 25 '10 (score 2) does work, except that redirection symbols and '&' cause syntax errors.
I think the best and simplest solution is the one posted by Sager Oct 8 '14 (score 0). Unfortunately, it has a typo: ‘"%a"’ should be ‘"%a%"’.
Here's a batch file based on Sager's answer. Redirection symbols and '&' in the input don't cause problems. The only problems I could find were caused by strings containing double quotes.
#echo off & setlocal enableextensions & echo.
set /p input=Enter a string:
SET "x=" & for /f "delims=0123456789" %%i in ("%input%") do set x=%%i
if defined x (echo Non-numeral: "%x:~0,1%") else (echo No non-numerals)
In addition to the remark about the error that occures when spaces are part of the users input. You can use errorlevel errorlevel=9165. It can be used for the spaces in a string or for the error handling of 'no' input.
Kind Regards,
Egbert
You might also like this one - it's short and easy. This one use the multiplication trick to set TestVal. Comparing TestVal against UserInput allows all numeric values to get through including zeroes, only non-numerics will trigger the else statement. You could aslo set ErrorLevel or other variables to indicate a failed entry
#ECHO OFF
SET TestVal=0
SET /P UserInput=Please Enter a Number:
SET /A TestVal="%UserInput%"*1
If %TestVal%==%UserInput% (
ECHO You entered the number %TestVal%
) else ECHO UserInput "%UserInput%" is not a number
GOTO EOF
:EOF
I know this is years old, but just to share my solution.
set /p inp=Int Only :
:: Check for multiple zeros eg : 00000 ::
set ch2=%inp%-0
if %inp% EQU 0 goto :pass
if [%inp%]==[] echo Missing value && goto :eof
if %inp:~0,1%==- echo No negative integers! && goto :eof
set /a chk=%inp%-10>nul
if %chk%==-10 echo Integers only! && goto :eof
:pass
echo You shall pass
:eof
Tested and working on Windows 8.
you can reinvent the wheel and grow a few white hairs doing string validation in batch, or you can use vbscript
strInput = WScript.Arguments.Item(0)
If IsNumeric(strInput) Then
WScript.Echo "1"
Else
WScript.Echo "0"
End If
save it as checkdigit.vbs and in your batch
#echo off
for /F %%A in ('cscript //nologo checkdigit.vbs 100') do (
echo %%A
rem use if to check whether its 1 or 0 and carry on from here
)
You can validate any variable if its number:
SET "var="&for /f "delims=0123456789" %i in ("%a") do set var=%i
if defined var (echo."NIC">nul) else (echo."number")
If you want some sort of a loop and default set up for that particular question, then here's my method for doing this.
Notes on the code within.
#echo off
setlocal EnableDelayedExpansion
set "ans1_Def=2"
:Q1
set /p "ans1=Opt 1 of 1 [Value 1-5 / Default !ans1_Def!]: "
:: If not defined section. This will use the default once the ENTER key has been
:: pressed and then go to :Q2.
if not defined ans1 (
echo/ & echo ENTER hit and the default used. Default is still: !ans1_Def! & echo/
set "ans1=!ans1_Def!" && goto :Q2 )
:: This section will check the validity of the answer. The "^[1-5]$" will work
:: for only numbers between one and five in this example but this can be changed
:: to pretty much suit the majority of cases. This section will also undefine
:: the ans1 variable again so that hitting the ENTER key at the question
:: will work.
echo %ans1%|findstr /r /c:"^[1-5]$" >nul
if errorlevel 1 (
echo/ & echo At errorlevel 1. Wrong format used. Default is still: !ans1_Def! & echo/
set "ans1=" && goto Q1
) else ( echo Correct format has been used. %ans1% is the one. && goto :Q2 )
:Q2
echo/
echo -----------------------------
echo/
echo Now at the next question
echo !ans1!
echo/
pause
exit
Try this:
set /p numeric=enter a number
(
(if errorlevel %numeric% break ) 2>nul
)&&(
echo %numeric% is numeric
)||(
echo %numeric% is NOT numeric
)
Just try this
#echo off
SET constNum=100
:LOOP
Set /p input=Please input a number less than %constNum% :
if "%input%" == "" echo Blank is not allowed & goto LOOP
SET "notNumChar="
for /f "delims=0123456789" %%i in ("%input%") do set notNumChar=%%i
if defined notNumChar (
echo %input% is a string
goto LOOP
) else (
REM Remove leading 0 if it has. eg: 08→8
FOR /F "tokens=* delims=0" %%A IN ("%input%") DO SET inputNum=%%A
)
REM Compare
if defined inputNum (
echo %inputNum%
if %inputNum% equ %constNum% & goto LOOP
if %inputNum% gtr %constNum% & goto LOOP
if %inputNum% lss %constNum% & goto CONTINUE
)
:CONTINUE
:: Your code here
:ASK
SET /P number= Choose a number [1 or 2]:
IF %number% EQU 1 GOTO ONE
IF %number% NEQ 1 (
IF %number% EQU 2 GOTO TWO
IF %number% NEQ 2 (
CLS
ECHO You need to choose a NUMBER: 1 OR 2.
ECHO.
GOTO ASK
)
)
It works fine to me. If he chooses numbers less or greater, strings, floating number etc, he wil receive a message ("You need to choose a NUMBER: 1 OR 2.") and the INPUT will be asked again.
#echo off
setlocal enableextensions enabledelayedexpansion
set /p UserInput=Enter a number:
set /a Test=UserInput
if !Test! EQU 0 (
if !UserInput! EQU 0 (
echo Number
) else (
echo Not a number
)
) else (
echo Number
)
yeaph everthing is great
but you forget about one little thing
0 also is a digit
;(
This is more of a user friendly way.
if %userinput%==0 (
cls
goto (put place here)
)
if %userinput%==1 (
cls
goto (put place here)
)
if %userinput%==2 (
cls
goto (put place here)
)
if %userinput%==3 (
cls
goto (put place here)
)
if %userinput%==4 (
cls
goto (put place here)
)
if %userinput%==5 (
cls
goto (put place here)
)if %userinput%==6 (
cls
goto (put place here)
)if %userinput%==7 (
cls
goto (put place here)
)
if %userinput%==8 (
cls
goto (put place here)
)
if %userinput%==9 (
cls
goto (put place here)
)
This can be used for any type of user input.
for me this is working for all non-zero values ..should i be cautious of some rare cases?
set /a var = %1
if %var% neq 0 echo "it is number"
pause

Resources