All option in choice command - batch-file

I am wondering if there is a nice and clean way to add a "select all choices" when building a choice menu in batch.
Currently I have the choice setup as clear item 1, clear item 2, clear item 3 (clear all), exit, and a timeout that the user cannot see.
If I have to I will just re-add all my code to the "clear all" area. I was hoping to see if there was a way to just have the "clear all" use the defined 1 and 2 and then go back to :start like everything else.
Answer: I took Aacini's idea of the "set option" and came up with an even simpler answer. I Changed "GOTO :start"to"GOTO :ClearCache" for the "Clear All Options". Then I added a "IF %ERRORLEVEL% neq 3 GOTO :start" and after that a "GOTO :ClearCredentials". This allowed me to keep less lines than the set option and I didn't have to move my code around to have it pass to the next process.
This should allow for multiple but different clear all options for future items.
#ECHO OFF
:start
ECHO 1. Clear IE, Chrome, Temp Cache
ECHO 2. Clear Credentials in IE, Chrome, and Windows
ECHO 3. Clear All Options
ECHO 4. Exit
CHOICE /N /C:12345 /T 15 /D 5 /M "Type the number to choose an option."
IF %ERRORLEVEL%==5 GOTO TIMEOUT
IF %ERRORLEVEL%==4 GOTO Exit
IF %ERRORLEVEL%==3 GOTO ClearAllOptions
IF %ERRORLEVEL%==2 GOTO ClearCredentials
IF %ERRORLEVEL%==1 GOTO ClearCache
GOTO :start
:ClearCache
ECHO Clearing Cache...
<code here>
pause
cls
IF %ERRORLEVEL% neq 3 GOTO :start
GOTO :ClearCredentials
REM ===-----------------------
:ClearCredentials
ECHO Clearing Credentials
<code here>
pause
cls
GOTO :start
REM ===-----------------------
:ClearAllOptions
ECHO Clearing All Options...
pause
cls
GOTO :ClearCache
pause
REM ===-----------------------
:Exit
ECHO Exiting...
<code here>
pause
EXIT
REM ===-----------------------
:TIMEOUT
cls
ECHO Exiting because no choices were made in 15 seconds
:END
timeout /t 5

This is a very simple way to do that:
#ECHO OFF
:start
set option=0
ECHO 1. Clear IE, Chrome, Temp Cache
ECHO 2. Clear Credentials in IE, Chrome, and Windows
ECHO 3. Clear All Options
ECHO 4. Exit
CHOICE /N /C:12345 /T 15 /D 5 /M "Type the number to choose an option."
GOTO Option-%ERRORLEVEL%
:Option-3 ClearAllOptions
ECHO Clearing All Options
set option=3
:Option-1 ClearCache
ECHO Clearing Cache...
<code here>
pause
cls
if %option% neq 3 GOTO :start
REM ===-----------------------
:Option-2 ClearCredentials
ECHO Clearing Credentials
<code here>
pause
cls
GOTO :start
REM ===-----------------------
:Option-4 Exit
ECHO Exiting...
<code here>
pause
EXIT
REM ===-----------------------
:Option-5 TIMEOUT
cls
ECHO Exiting because no choices were made in 15 seconds
:END
timeout /t 5

Related

how to give a .bat code line a time limit?

I want to put a 30s time limit for the :choice Y/N/P and after the time is up goto :start
The code I have need help for the timeing thing
#echo off
:start
echo AmishCraft will start
TIMEOUT /T 5
echo (%time%)
java -Xms2048M -Xmx4096M -jar server.jar
call C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe
ping 1.1.1.1 -n 1 -w 3000 >nul
:choice
set /P a=do you want to restart? Yes No Pause [Y/N/P]?
if /I "%a%" EQU "Y" goto :restart
if /I "%a%" EQU "N" goto :stop
if /I "%a%" EQU "P" goto :pause
goto :start
:restart
cls
echo server will restart
cls
goto :start
:stop
cls
echo closing server
TIMEOUT /T 5
exit
cls
echo server is paused
:pause
:choice
set /P a=do you want start? Restart Stop [R/S]?
if /I "%a%" EQU "R" goto :restart
if /I "%a%" EQU "S" goto :stop
goto :start
pause
/T is the timeout switch for choice.
/D is the switch to define the default errorlevel / option to set if the
time Elapses.
Example:
CHOICE /T 5 /N /C 1234 /M "Select Option 1,2,3 or 4" /D 1
Applies a timeout of 5 seconds, with the errorlevel being set to option 1, equal to errorlevel 1 in this instance.
/N Hides the default Choice Prompt String.
/M Allows you to Define your own Prompt string
/C Allows alphanumerical characters to be defined as Choice options
Note:
Errorlevel is Set from Left to Right with regards to listed options.
After the Choice Command Errorlevel Needs to be Assessed From Highest to lowest
OR
Used Directly; Such as in a Goto :LabelName%errorlevel% Command
* Response to comment *
CHOICE /C 123 /T Timeout 25 /D goto :start /M 1 choice menu 25s
IF %ERRORLEVEL% EQU 1 goto :choice1
There are multiple errors in the above.
/T Timeout 25 should be: /T 25
Timeout is implicit in the /T switch and does NOT form a part of correct usage of the choice command.
/D goto :start should be: /D 1 OR /D 2 OR /D 3
Only the defined /C options should be used following the /D switch
/M 1 choice menu 25s is incorrect.
The prompt after /M should be encased in Doublequotes: "[1] Option 1. [2] Option 2. [3] Option 3."
Errorlevel Assessment should be done on the Line After the CHOICE Command.
Again, to be clear, Assesment should be done from Highest to Lowest. When errorlevel is Assessed following Choice it is actually interpreted as If ERRORLEVEL GTR n , Despite being scripted Using If ERRORLEVEL n
An example of the Correct usage of all of the above:
#echo off
:menu
cls
CHOICE /N /T 25 /C 123 /M "[1] Option 1. [2] Option 2. [3] Start." /D 3
IF ERRORLEVEL 3 (
GOTO :start
) else (
GOTO :choice%errorlevel%
)
:start
ECHO( You are at the start
Pause
GOTO :menu
:choice1
ECHO( You are at option 1
Pause
GOTO :menu
:choice2
ECHO( You are at option 2
Pause
GOTO :menu

In batch my menu will not work

I was trying to create a simple menu system with batch but i can't tell if it's the 'goto' or the input part that i messed up on. help will be appreciated!
#echo off
cls
echo ==============MENU==============
echo 1.
echo 2.
echo 3.
echo choose.
set/p "menuInput"
if %menuInput%==1 (goto :1)
if %menuInput%==2 (goto :2)
if %menuInput%==3 (goto :3)
else echo error
:1 echo 1
:2 echo 2
:3 echo 3
The syntax of set /p is incorrect. Use set /? to read the help.
The parentheses around (goto :1) don't buy you anything.
The else is both syntactically incorrect (must be on the same logical line as the if) and useless (because if the if had succeeded control would have been passed to :3).
You are missing a bunch of exit /b or goto :eof in order to prevent control falling through the options.
ok i updated your code now this shold work
code here
#echo off
:menu
cls
title menu
echo ==============MENU==============
echo 1.
echo 2.
echo 3.
set /p menuInput=? 1-3
if %menuInput% EQU 1 goto 1
if %menuInput% EQU 2 goto 2
if %menuInput% EQU 3 goto 3
goto error
:1
echo1
pause
:2
echo2
pause
:3
echo3
pause
:error
echo error press 1-3
pause>nul
goto menu
As mentioned by #AlexP,your syntax of set /p is incorrect
you need to use set < space > /p < space > userinput=
and not set/p and there should be = sign after your variable name
SET /P variable=[promptString]
Read More about using SET & IF ELSE and also CHOICE
(edit- removed misleading code for error check)
sample batch with menu using Choice and SET /P IF Else while choosing option from menu.
Example 1 using IF ELSE (input error check)
#echo off
::Your Menu to choose from
:menu
cls
echo ==============MENU==============
echo 1.command menu item 1
echo 2.command menu item 2
echo 3.command menu item 3
echo.
set /p userinput=
if %userinput%==1 (
goto 1
) else if %userinput%==2 (
goto 2
) else if %userinput%==3 (
goto 3
) else (
goto error
)
:1
echo command 1
pause>nul
goto menu
:2
echo command 2
pause>nul
goto menu
:3
echo command 3
pause>nul
goto menu
::Incorrect Input go back to menu
:error
echo Incorrect User Input
pause>nul
goto menu
:end
exit
Example 2 using CHOICE command (no error input check)
#echo off
::Your Menu to choose from
:menu
cls
echo ==============MENU==============
echo 1.command menu item 1
echo 2.command menu item 2
echo 3.command menu item 3
::check and limit user input to selection
choice /C 123 /N /M "Your Selection"
IF "%ERRORLEVEL%"=="1" goto 1
IF "%ERRORLEVEL%"=="2" goto 2
IF "%ERRORLEVEL%"=="3" goto 3
:1
echo command 1
pause>nul
goto menu
:2
echo command 2
pause>nul
goto menu
:3
echo command 3
pause>nul
goto menu
Wrong is set /p.
try set /p menuInput =

My batch script doesn't use if command correctly

I've spent a few days trying to get this batch script to work, but it just does not seem to work properly. It seems to just do whatever it wants after it prompts me to set a variable and i set it.
For example, I might enter n when it says that it doesn't seem to exist, and it will just end the script like it should. But if I re-open it, and it says the same thing as before, and I enter n again, it might just jump to :DeleteCalc, as if I typed y.
Here's my script:
#echo off
:Begin
color fc
title My script
cls
if not exist "C:\calc.exe" (
echo calc.exe doesn't seem to exist. Attempt deletion anyway? ^(Y/N^)
set "calcnotexist="
set /p "calcnotexist="
::This command checks to see if the user inputs a quotation mark. If they do, it echos that quotes cannot be inputted.
setlocal EnableDelayedExpansion
if not !calcnotexist!==!calcnotexist:^"=! set "calcnotexist="
endlocal & if "%calcnotexist%"=="" (
echo ERROR - Quotes cannot be entered.
pause
goto Begin
)
if /i "%calcnotexist%"=="Y" (
echo.
goto DeleteCalc
)
if /i "%calcnotexist%"=="Yes" (
echo.
goto DeleteCalc
)
if /i "%calcnotexist%"=="N" goto End
if /i "%calcnotexist%"=="No" goto End
echo ERROR - Unrecognized input
pause
goto Begin
)
:calcDoesExist
title My script
cls
echo calc.exe found. Delete? ^(Y/N^)
set "calcexist="
set /p "calcexist="
::This command checks to see if the user inputs a quotation mark. If they do, it echos that quotes cannot be inputted.
setlocal enabledelayedexpansion
if not !calcexist!==!calcexist:^"=! set "calcexist="
endlocal & if "%calcexist%"=="" (
echo ERROR - Quotes cannot be entered.
pause
goto calcDoesExist
)
if /i "%calcexist%"=="Y" goto DeleteCalc
if /i "%calcexist%"=="Yes" goto DeleteCalc
if /i "%calcexist%"=="N" goto End
if /i "%calcexist%"=="No" goto End
echo ERROR - Unrecognized input
pause
goto calcDoesExist
:DeleteCalc
cls
echo Deleting...
if not exist C:\calc.exe goto Success
del /f /q C:\calc.exe >nul 2>nul
if not exist C:\calc.exe goto Success
echo Fail!
echo.
echo calc.exe could not be deleted.
echo.
pause
goto End
:Success
echo Deleted!
echo.
echo calc.exe successfully deleted.
echo.
pause
goto End
:End
exit /b
What could I possibly be doing wrong?
Thanks
P.S. I tested this by opening CMD and running the batch script multiple times in there. (but it also doesn't work right when just double clicking it)
If you restructure your script there will be no need for the extended If blocks and therefore no necessity to EnableDelayedExpansion. Also if you use Choice you will not have to do all of the verification of responses.
Example:
#Echo Off
Title My script
Color FC
:Begin
If Exist "C:\calc.exe" GoTo calcDoesExist
Echo(calc.exe doesn't seem to exist.
Choice /M "Attempt deletion anyway"
If ErrorLevel 3 (ClS & GoTo Begin)
If ErrorLevel 2 GoTo End
If ErrorLevel 1 GoTo Success
GoTo End
:calcDoesExist
Echo(calc.exe found.
Choice /M "Delete"
If ErrorLevel 3 (ClS & GoTo calcDoesExist)
If ErrorLevel 2 GoTo End
If ErrorLevel 1 GoTo DeleteCalc
GoTo End
:DeleteCalc
ClS
Echo(Deleting...
Del /A /F "C:\calc.exe">Nul 2>&1
If Not Exist "C:\calc.exe" GoTo Success
Echo(Fail!
Echo(
Echo(calc.exe could not be deleted.
GoTo End
:Success
Echo(
Echo(Deleted!
Echo(
Echo(calc.exe does not exist.
:End
Echo(
Echo(Exiting...
Timeout 3 /NoBreak>Nul
Exit /B

Avoiding Spaghetti Code

I've been reading how to avoid spaghetti code in batch files.
In the example of what spaghetti code is, I realized that the batch file that I use when I logon almost fits this example. Could someone please help me make my batch file not have spaghetti code?
#ECHO OFF
CLS
:MENU
echo Welcome %USERNAME%
echo 1 - Start KeePass
echo 2 - Backup
echo 3 - FireFox
echo 4 - Exit
SET /P M=Please Enter Selection, then Press Enter:
IF %M%==1 GOTO StarKeePass
IF %M%==2 GOTO Backup
IF %M%==3 GOTO FireFox
IF %M%==4 GOTO :EOF
GOTO MENU
:StarKeePass
SET keePass="%USERPROFILE%\KeePass\KeePass-2.30\KeePass.exe"
SET kdb="%USERPROFILE%\KeePass\PasswordDatabase\PasswordDatabase.kdbx"
echo I'll start KeePass for You
START "" %keePass% %kdb%
GOTO MENU
:Backup
SET backup="%USERPROFILE%\backup.bat"
call %backup%
GOTO MENU
:FireFox
cd "C:\Program Files (x86)\Mozilla Firefox\"
start firefox.exe
GOTO MENU
In this case, if you want to use subroutines you should do this:
#ECHO OFF
CLS
:MENU
echo Welcome %USERNAME%
echo 1 - Start KeePass
echo 2 - Backup
echo 3 - FireFox
echo 4 - Exit
SET /P M=Please Enter Selection, then Press Enter:
IF %M%==1 CALL :StartKeePass
IF %M%==2 CALL :Backup
IF %M%==3 CALL :FireFox
IF %M%==4 GOTO :EOF
GOTO MENU
:StartKeePass
SET "keePass=%USERPROFILE%\KeePass\KeePass-2.30\KeePass.exe"
SET "kdb=%USERPROFILE%\KeePass\PasswordDatabase\PasswordDatabase.kdbx"
echo I'll start KeePass for You
START "" %keePass% %kdb%
GOTO :EOF
:Backup
SET "backup=%USERPROFILE%\backup.bat"
call %backup%
GOTO :EOF
:FireFox
cd "C:\Program Files (x86)\Mozilla Firefox\"
start firefox.exe
GOTO :EOF
Note that I changed a few things. Instead of goto... goto menu, you should use call :label goto :eof/ exit /b. Besides that, you had a spelling error StartKeePass, and instead of set variable="value", it's better to use set "variable=value". This will also accept spaces in the value, but it won't add quotes to your variable
Next time you should probably post this to code review, because these things aren't really errors
If you wanted to remove gotos altogether, you can simply call the script again to keep using it. Also, look into the choice command if you're using a version of Windows later than XP, since it will eliminate the need to check if the user entered invalid input.
#echo off
cls
echo Welcome %USERNAME%
echo 1 - Start KeePass
echo 2 - Backup
echo 3 - FireFox
echo 4 - Exit
choice /C:1234 /M "Please enter your selection: " /N
:: The first option listed by choice's /C option will return an errorlevel value of 1, the second 2, and so on
if %errorlevel% equ 1 (
SET keePass="%USERPROFILE%\KeePass\KeePass-2.30\KeePass.exe"
SET kdb="%USERPROFILE%\KeePass\PasswordDatabase\PasswordDatabase.kdbx"
echo I'll start KeePass for You
START "" %keePass% %kdb%
)
:: I've converted these to one-liners simply for personal preference.
:: You can keep these the way you had them if you put them inside of parentheses like with option 1.
if %errorlevel% equ 2 call "%USERPROFILE%\backup.bat"
if %errorlevel% equ 3 start "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
if %errorlevel% equ 4 exit /b
:: Calls this script again, simulating a goto :MENU
:: Personally, I'd stick with a label and a goto in this instance,
:: but this is how you could do it if you don't want to use goto at all
call %0
If each choice the user can make is fairly simple (i.e. it can be simplified to one or two commands), you might want to code this way; otherwise, definitely use subroutines like Dennis suggested.
My take on organizing this, added a reset to m variable, allowed some accidental input to be dealt with, and made it all checked in one block of code.
Nothing wrong with 'Dennis van Gils' answer, figured i would show you a different approach.
#echo off
setlocal enableDelayedExpansion
:menu
set "m="
cls
echo/Welcome !username!
echo/
echo/1 - Start keepass
echo/2 - Backup
echo/3 - Firefox
echo/4 - Exit
echo/
set /p "m=Please enter selection, then press enter:"
if not defined m (
cls
echo/Error: Empty input.
pause
) else (
if "!m!" equ "1" (
set "keepass=!userprofile!\keepass\keepass-2.30\keepass.exe"
set "kdb=!userprofile!\keepass\passworddatabase\passworddatabase.kdbx"
echo/I'll start keepass for you
start "" !keepass! !kdb!
) else (
if "!m!" equ "2" (
set "backup=!userprofile!\backup.bat"
call !backup!
) else (
if "!m!" equ "3" (
cd "c:\program files (x86)\mozilla firefox\"
start firefox.exe
) else (
if "!m!" equ "4" (
goto :eof
) else (
cls
echo/Error: ["!m!"] not recognized.
pause
)
)
)
)
)
goto :menu
Note: echo/ is used as a habit, as echo: and echo\ i mistake for parts of a file path/url, and echo. is so painstakingly noted for its longer command time.
Also, i prefer using ! over % along with setlocal enableDelayedExpansion by pure preference, and ease of block coding.

Batch opening wrong file type

So here's my ENTIRE code:
#echo off
cls
color fc
:Start
cls
echo Welcome to -{GAMELOADER}-
set/p u=Username:
if %u%==username goto Correct1
if not %u%==username goto Incorrect
:Incorrect
cls
echo You Have Entered Incorrect Pass And/Or Username!
set/p t=Try Again? (Y/N)
if %t%==Y goto Start
if %t%==y goto Start
if %t%==N goto Quit
if %t%==n goto Quit
:Correct1
set/p p=Password:
if %p%==password goto Open
if not %p%==password goto Incorrect
:Open
cls
echo Games:
echo ------------------------
echo [1]Kerbal Space Program
echo ------------------------
set/p g=Choice:
if %g%== 1 goto KSPEnd
:KSPEnd
start "" "C:\Program Files (x86)\Steam\steamapps\common\Kerbal Space Program\KSP.exe"
cls
goto Quit
:Quit
cls
echo Goodbye
Timeout 1
But the code opens the .exe AND a .txt file with exactly the same name. I can't rename the files. So basically i'm asking how to open a specific file type.
Thanks
Instead of starting C:\....\KSP.exe, first go to the right directory, then start KSP:
cd "C:\Program Files (x86)\Steam\steamapps\common\Kerbal Space Program"
KSP.exe
Ok I've got two things for you. Firstly I'll give you you desired solution.
Treat it like an operatable program
rem To start Kerbal Space Program:
set Path=C:\Program Files (x86)\Steam\steamapps\common\Kerbal Space Program;%Path%
start KSP
Thats it. Really.
Secondly:
Use the Choice command
you keep on using set /p where choice would be much better.
Just to be convenient I redid you code with everything I would do. Have fun!
Code :
#echo off
cls
color fc
title -{GAMELOADER}-
:Start
echo Welcome to -{GAMELOADER}-
set/p u=Username:
if %u%==username goto Correct1
if not %u%==username goto Incorrect
set Er=Userid
goto :Crash
:Incorrect
cls
echo You Have Entered Incorrect Pass And/Or Username!
choice /c yn /m "Try Again?"
if %errorlevel%==1 goto Start
if %errorlevel%==2 goto Quit
set Er=Loop-End_of_stream
goto :Crash
:Correct1
set/p p=Password:
if %p%==password goto Open
if not %p%==password goto Incorrect
set Er=Passid
goto :Crash
:Open
cls
echo Games:
echo ------------------------
echo [1]Kerbal Space Program
echo ------------------------
echo.
Choice /c 1 /m "Game: "
if %errorlevel%==1 goto KSPEnd
set Er=Gameid
goto :Crash
:KSPEnd
set Path=C:\Program Files (x86)\Steam\steamapps\common\Kerbal Space Program;%Path%
start KSP
goto Quit
set Er=End_of_file___UNKNOWN
goto :Crash
:Quit
cls
echo Goodbye
Timeout 1
Exit
:Crash
Rem Always useful :)
Echo Program has crashed Error: %Er%
Pause
Exit
Hope that helped. Mona

Resources