If statement in batch file - user chooses option - windows

New to batch/sql files. Thanks for you help.
What im trying to do:
user picks option 1, runs my sql file.
user picks 2, exits program.
user enters nothing or invalid option, ECHO "invalid option".
Problem: anything I type will exit my program. What am I doing wrong?
ECHO 1 - Show Report
ECHO 2 - Exit
SET choice=""
SET /P input=Your choice:
IF "%input%"=="1" (
GOTO :sql file
) ELSE (
IF "%input%"=="2" (
GOTO :Exit
)
) ELSE (
IF "%input%"=="" (
ECHO Invalid option chosen.
)
)
PAUSE

Just use the choice command, its instructions are available by entering choice /? at the Command Prompt.
#ECHO OFF
ECHO 1 - Show Report
ECHO 2 - Exit
CHOICE /C 12 /M "Your choice"
IF ERRORLEVEL 2 GOTO :EOF
REM This line is your SQL report code
PAUSE
If you still wanted to use, what in your case I believe is the wrong Set /P input method, then something like this should be relatively robust, given that your end user is free to enter whatever they like as input, mischievous or harmful intent included:
#ECHO OFF
ECHO 1 - Show Report
ECHO 2 - Exit
:GETInput
SET "input="
SET /P "input=Your choice: "
2>&1 SET input | FINDSTR /XR "input=[12]" 1>NUL || (
ECHO Invalid option chosen
GOTO GETInput
)
IF %input% EQU 2 GOTO :EOF
REM This line is your SQL report code
PAUSE

There is one extract closing bracket [Line #12] inside nested if..else. Also, as far as i know, your label :sql file should not contain space and you must declare it inside the batch file (Same for label :Exit)
I did few changes in your code to make it work
#echo off
:Main
cls
ECHO 1 - Show Report
ECHO 2 - Exit
SET choice=""
SET /P input=Your choice:
IF "%input%"=="1" (
GOTO :SQLReport
) ELSE IF "%input%"=="2" (
GOTO :EOF
) ELSE (
ECHO.
ECHO Invalid option chosen.
pause
GOTO :Main
)
:SQLReport
ECHO.
ECHO Running SQL Report...
GOTO :EOF
:EOF

Related

Batch File Resume with Prewritten Arguments

I have two batch files one batch files calls another. The one that calls the other is called install.bat, and the other controller.bat.
The contents of install.bat are as follows:
start controller.bat a.exe b.exe
Then the controller.bat file operates as such:
#echo off
:: Check if the first argument is passed
if "%~1"=="" (
echo "No first argument passed"
) else (
set first_arg=%~1
)
:: Check if the second argument is passed
if "%~2"=="" (
echo "No second argument passed"
) else (
set second_arg=%~2
if not "%~1" == "" (
set current=one
) else(
echo twob >%~dp0current.txt
)
)
call :Resume
goto %current%
goto :eof
:one
::Add script to Run key
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /d %~dpnx0 /f
echo two >%~dp0current.txt
echo -- Section one --
echo "update will start"
start /wait %second_arg%
echo "update done"
pause
shutdown -r -t 0
goto :eof
:two
echo three >%~dp0current.txt
echo -- Section two --
echo "updating now"
Start /wait %first_arg%
echo "Update Finish"
pause
shutdown -r -t 0
goto :eof
:twob
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /d %~dpnx0 /f
echo three >%~dp0current.txt
echo -- Section two --
echo "updating now"
Start /wait %first_arg%
echo "Update Finish"
pause
shutdown -r -t 0
goto :eof
:three
::Remove script from Run key
reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /f
del %~dp0current.txt
echo -- Section three --
pause
goto :eof
:resume
if exist %~dp0current.txt (
set /p current=<%~dp0current.txt
) else (
set current=one
)
The problem it is not working well it jumps into twob and then straight to three. It is supposed to show the intermediate steps to a user to show the updates are occurring.
I am expecting it to be able to read if one argument is supplied let's say the second and not the first and still do the jumps to right labels. Right now, the labels are a bit mixed up when I supply both args %~1 and %~2.

Why I can't get output from this batch script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This program stops automatically! When I enter correct name and password (i.e it is not executing from 8th line). Please check if I made any mistakes.
#echo off
:s
set t=0
set /p a= enter your name
set /p b= enter your password
if %a%==andrew(set /a t=%t%+1)
if %b%==123 (set /a t=%t%+2 )
if %t%==3 ( echo welcome andrew
echo ---------------------------------------------------------------------------
:r
set /p c=want to change your settings -yes -no
if %c%==no (echo ok
goto e
)
if %c%==yes (set /p p= what you want to change -name(1) -password(2)
if %p%==1 (set /p a=enter name to change)
if %p%==2 (set /p a=enter password to change)
)
)
if %t%==2 echo %a% is not authorised
if %t%==1 echo enter correct password
if %t%==0 echo Both name and id are wrong enter again
goto r
goto s
:e
pause
Set #echo on and you may see something like this when the script is executed:
--> set t=0
--> set /p a= enter your name
enter your nameandrew
--> set /p b= enter your password
enter your password123
--> if andrew == andrew(set /a t=0+1)
--> if 123 == 123 (set /a t=0+2 )
(echo was unexpected at this time.
--> if ==no (echo ok
The script stopped with error:
(echo was unexpected at this time.
Line 7 showed OK:
if 123 == 123 (set /a t=0+2 )
though, next command output seen is:
if ==no (echo ok
which means %c% is undefined as you can see a value missing left of the == that caused the error.
This could be happening as to the opening parentheses in line 8:
if %t%==3 ( echo welcome andrew
The parser will see the opening parentheses and will keep reading the lines until it reaches a closing parentheses. It will substitute the percentage enclosed variables before execution. This makes %c% undefined as %c% is not defined before the opening parentheses on line 8 began the read.
So it seems the parser read:
if %t%==3 ( echo welcome andrew
echo ---------------------------------------------------------------------------
:r
set /p c=want to change your settings -yes -no
if %c%==no (echo ok
goto e
)
And does variable substitution of known values of t=3 and c=:
if 3==3 ( echo welcome andrew
echo ---------------------------------------------------------------------------
:r
set /p c=want to change your settings -yes -no
if ==no (echo ok
goto e
)
The error of if ==no (echo ok is shown.
Your question in the title:
why i cant get output from this batch script?
It is the opening parentheses in line 8. So one should ask thy self... What is that opening parentheses doing there in line 8 when it will include a label :r and a set /p that sets a variable c that can cause an undefined variable?
If the opening parentheses is meant to be there, view set /? that may show an example like:
set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "%VAR%" == "after" #echo If you see this, it worked
)
The example code and the details in set /? informs you how set variables work.
The label between the parentheses would still be a concern as it can cause error in a read block of code.
There is a couple of things. Do not set single character variables or label names. rather use set vara than using set a but making things recognisable like using variables that means something, makes things less confusing.
when matching variables with a value using == double quote each side. i.e if "%var" == "123"
For selection, use choice instead of set /p
Also, when using set /a the better way to add is set /a vart+=1 instead of set /a %vart%+1
This should do more or less what you want.
#echo off
:start
set vart=0
set /p "name=Enter your name: "
set /p "pass=Enter your password: "
if /i "%name%" == "andrew" set /a vart+=1
if "%pass%" == "123" set /a vart+=2
if %vart% equ 3 echo welcome andrew
echo ---------------------------------------------------------------------------
:settings
choice /c YN /m "Change your settings?"
if %errorlevel% equ 0 goto opt0
goto opt%errorlevel%
:opt0
echo You Pressed CTRL+C and selected "N"
exit /b 1
:opt2
pause
goto :eof
:opt1
choice /c UP /m "Change your User or Password?"
if %errorlevel% equ 0 goto opt0
goto chng%errorlevel%
:chng2
set /p "name=Enter name to change: "
goto :eof
:chng1
set /p "pass=Enter password to change: "
if %vart% equ 2 echo %a% is not authorised
if %vart% equ 1 echo enter correct password
if %vart% equ 0 echo Both name and id are wrong enter again
goto settings
goto start
Please read the syntax of the commands, such as if and set before posting.
Addressing some problems in your code:
First,
if %a%==andrew(set /a t=%t%+1)
is intercepted by cmd.exe as:
if %a% is andrew(set, run a command called /a t=%t%+1. Also, please double quote all set /p ...= in your script, even though it can't handle poison characters.
Second, you have unescaped closing parenthesis ) in your if, which can cause interception errors.

Unable to load a .cmd from a batch file

I recently played the game "Dictator" and wanted to recreate it in a batch script. I just began creating it when I ran into an issue. I have made programs which allow the user to save their progress and load it. I copied this code from a different program and put it in mine. Saving does seem to work but when i edit the save file (.cmd) and edit one of the saved variables, once I load that file nothing seems to happen. For example I saved one file called key.cmd and edited it to make the "pol" variable equivalent to 100. Once I loaded that file it did say loaded but the pol variable was still set to the default (10). I dont understand as I have made a folder called save and key.cmd file is inside it. I have used my save and load code multiple times in the past and have never had any issues. Please help! Here is my code:
:Setup
#echo off
title Dictator
color 0a
:Save Variables
set pol=10
set bui=10
set low=10
set cor=10
set peo=10
set cri=10
:Main
cls
echo 1 - Save
echo 2 - Load
echo 3 - Police - %pol%
echo 4 - Buissnes Men - %bui%
echo 5 - Lower Government - %low%
echo 6 - Corruption - %cor%
echo 7 - People - %peo%
echo 8 - Criminals - %cri%
choice /c 12345678 /n /m ">>> "
if %errorlevel% equ 1 goto Save
if %errorlevel% equ 2 goto load
:Save
cls
set /p pin="PIN: "
(
echo set pol=%pol%
echo set bui=%bui%
echo set low=%low%
echo set cor=%cor%
echo set peo=%peo%
echo set cri=%cri%
) >> saves\%pin%.cmd
echo SAVED
pause >nul
goto main
:Load
cls
set /p pin="PIN: "
if exist saves\%pin%.cmd (
call saves\%pin%.cmd
echo %pol%
echo LOADED
pause >nul
) else (
echo INCORRECT PIN
pause >nul
)
goto main
At :Load you need to allow spaces in the file name. Most users won't know of this weakness, but in order to allow spaces (and a few other 'special' characters) to be read in the user input without breaking it, you need to add setlocal enableextensions enabledelayedexpansion to the beginning of your batch file and make the set /p pin="PIN: " statement into set /p "pin=PIN: " and replace the %'s with !'s where it calls for %pin%.
In the end, your code should look like:
:Setup
setlocal enableextensions enabledelayedexpansion
#echo off
title Dictator
color 0a
:Save Variables
set pol=10
set bui=10
set low=10
set cor=10
set peo=10
set cri=10
:Main
cls
echo 1 - Save
echo 2 - Load
echo 3 - Police - %pol%
echo 4 - Buissnes Men - %bui%
echo 5 - Lower Government - %low%
echo 6 - Corruption - %cor%
echo 7 - People - %peo%
echo 8 - Criminals - %cri%
choice /c 12345678 /n /m ">>> "
if %errorlevel% equ 1 goto Save
if %errorlevel% equ 2 goto load
:Save
cls
set /p "pin=PIN: "
(
echo set pol=%pol%
echo set bui=%bui%
echo set low=%low%
echo set cor=%cor%
echo set peo=%peo%
echo set cri=%cri%
) >> saves\!pin!.cmd
echo SAVED
pause >nul
goto main
:Load
cls
set /p "pin=PIN: "
if exist saves\!pin!.cmd (
call saves\!pin!.cmd
echo %pol%
echo LOADED
pause >nul
) else (
echo INCORRECT PIN
pause >nul
)
goto main

Store a sentence in a variable (batch)

I am making a batch file, and whenever their is a user input field, which the user enter a word or a sentence and it get stored in a text file. I made all the job done.
But when the user's input is more than 1 word, it gives the following error:
*second word* was unexpected.
How can this be solved?
#echo off
color f0
:menu
cls
echo Batch Editor
echo Choose what you want to do:
echo 1) New Document
echo 2) Load existing document
echo 3) Learn How to Use
echo 4) Exit
set /p menu=
if %menu%==1 goto new
if %menu%==2 goto load
if %menu%==3 goto learn
if %menu%==4 goto exit
if [%1]==[] goto learn
echo Invaild Code
pause
goto menu
:new
cls
echo You have chosen to start a new document.
echo But please note that is impossible to know how to code
echo without seeing the "How to Learn" section.
echo Choose:
echo 1) Continue anyways
echo 2) Go to the "How to Learn" section
echo 3) Exit
set /p type=
if '%type%'=='' goto new
if %type%==1 goto newdoc
if %type%==2 goto learn
if %type%==3 goto exit
echo Invaild Key
pause
goto new
:newdoc
cls
set /p input=
if %input%==Qsave goto saving
if %input%==qsave goto saving
if %input%==qSave goto saving
if %input%==QSAVE goto saving
goto newdoc1
pause
:newdoc1
set /p chosen=
if '%chosen%'==''(
goto newdoc2)
else if "%chosen%"=="Qsave" (
goto saving)
else if "%chosen%"=="qsave" (
goto saving)
else if "%chosen%"=="qSave" (
goto saving)
else if "%chosen%"=="QSAVE" (
goto saving)
else (
goto newdoc2)
:newdoc2
set /p chosen=
if '%chosen%'==''(
goto newdoc1)
else if %chosen%==Qsave (
goto saving)
else if %chosen%==qsave (
goto saving)
else if %chosen%==qSave (
goto saving)
else if %chosen%==QSAVE (
goto saving)
else (
goto newdoc1)
:saving
cls
echo Saving
pause
:load
echo LOADING
pause
:learn
echo Learn
pause
:exit
cls
set /a exiting=0
echo Are you sure you want to exit?
echo Choose:
echo 1)Exit
echo 2)Go Back to the Main Menu
set /p exiting=
if %exiting%==1 exit
if %exiting%==2 goto menu
echo Invaild key
pause
goto exit
pause
exit
You really should post what you currently have, if all you're trying to do is store user inputted text to a text file, something like this might help?
SET /P Answer=Say somthing witty!
ECHO %Answer%>Response.txt
set var=Alpha beta Gamma
if %var%==whatever
is translated to:
if Alpha beta Gamma==whatever
IF Syntax is IF <Argument1> <comparator> <Argument2> <command>
Argument1 is Alpha, Comparator is beta - wait, this is wrong...
It leads to "beta was unexpected", because there should be a compatator (==), not an Argument.
Better Syntax:
if "%var%"=="whatever"
is translated to:
if "Alpha beta Gamma"=="whatever"
Argument1 is "Alpha beta Gamma", Comparator is ==, Agrument2 is "whatever" - fine Syntax.
Sample menu where there are only three possible choices plus one covering mistype:
#echo off
:retry
cls
Unset the variable M
set M=
If nothing typed, then set M to 4
SET /P "M=Type 1 for pizza, 2 for soup or 3 for exit, then press ENTER: " || set "M=4"
Here we use variable substring. See http://ss64.com/nt/syntax-substring.html
IF [%M:~0,1%]==[1] goto pizza
If M are not set to 1, then go to the next line, etc...
IF [%M:~0,1%]==[2] goto soup
If M are not set to 1 or 2 then check if it's set to 3, there is the last IF statement, we can now use else to cover everything else in the variable M
IF [%M:~0,1%]==[3] (
echo Bye...
#timeout /T 1 /nobreak >NUL
exit /b 0
) else (
goto :retry
)
:pizza
echo Pizza
goto :EOF
:soup
echo Soup
goto :EOF
Edit: My if statement was a bit redundant, see the revision history to see what I mean.

Syntax of the command is incorrect in batch?

The cmd.exe keeps giving me a The syntax of the command is incorrect error when I run the following codes. Whats wrong with it?
code:
#echo off
setlocal enabledelayedexpansion
CALL ant clean build compile
REM loop thru/Run ALL .properties file names from "ExecutionSDKTest_10.2.2" folder
:labelNextTest
FOR %%G in (C:\ExecutionSDKTest_10.2.2\*.properties) DO (
pause
Set fileName=%%~nxG
rem fileName==ENG-822.properties
set testName=!fileName:~0,7!
rem testName==ENG-822
set testNum=!fileName:~4,3!
REM testNum==822
ECHO Please Create: !testName!_Ref.properties.txt in C:\ExecutionSDKTest_10.2.2\Logs
echo Running:!fileName!
java -jar Test.jar !fileName! > Logs\!fileName!.log
set logPath="C:/ExecutionSDKTest_10.2.2/Logs/!fileName!.log"
set refLogPath="C:/ExecutionSDKTest_10.2.2/Logs/!testName!_Ref.properties.txt"
REM if Ref exists check Line by line
if EXIST !refLogPath!(
Call Perl TestProp1RefcheckLines.pl !fileName! !testName!
) else (
rem if ref does NOT exist check one important line
rem returns case number to check for
perl.exe c:\ExecutionSDKTest_10.2.2\TestProp1noRefCases.pl !testNum!
set lineCase=!ERRORLEVEL!
echo linecase is !lineCase!
rem set LineCase to one, two, three or four, depending on case number
FOR /F "tokens=*" %%B in (!logPath!) Do (
set logLine=%%B
rem check line >> : "...job status:..."
if /i "!logLine:~11,33!"=="... STATUS REPORT: ...Job status:"(
if "!lineCase!" =="1"(
if /i "!logline:~32!" == "job status: job finished_error" goto labelPass
)
if "!lineCase!"=="2" (
if /i "!logLine:~32!" == "Job status: job QUEUED" goto labelPass
)
if "!lineCase!"=="4"(
if /i "!logLine:~32!" == "job Execution Finished Successfully" goto labelPass
)
) else (
if /i "!logLine:~11,33!"=="Error initializing the connection" goto labelPass
if /i "!logLine!" == "Exception in thread ""main"" java.lang.IllegalArgumentException: timeout value is negative" goto labelPass
)
)
goto labelFail
)
)
pause
REM Test Passed or Failed
:labelFail
echo !TestName! FAILED due to the above incorrect line
goto labelNextTest
:labelPass
Echo !TestName! PASSED
goto labelNextTest
You're missing a few crucial spaces. In these lines:
if EXIST !refLogPath!(
if /i "!logLine:~11,33!"=="... STATUS REPORT: ...Job status:"(
if "!lineCase!" =="1"(
if "!lineCase!"=="4"(
there must be a space placed before the parenthesis ( !
Yes, batch scripts are very hard to debug. But really, the script could look prettier (indented properly, etc...).

Resources