Page 1 of 1

How to ask for input

Posted: 07 Mar 2023 18:41
by Docfxit
In this code I'm asking for a drive letter:

Code: Select all

:TryAgain
cls

::Windows 10 drive
Set Drive=
echo.
echo ===============================================================================
echo.  Enter the Letter of the drive Windows is on: Example C
echo ===============================================================================
set /p Drive= ^> Enter Drive:
@Echo On
if [%Drive%]==[] echo.&echo Invalid User Input&echo.&pause&goto :TryAgain
if /I %Drive% leq C If /I %Drive% geq Z echo.&echo Invalid User Selection&echo.&pause&goto :TryAgain
if /I %Drive% geq C & if %Drive% leq Z goto :Next1
GoTo :TryAgain
:Next1
When I run it I get an error: & was unexpected at this time.
This is the output I get:

Code: Select all

===============================================================================
  Enter the Letter of the drive Windows is on: Example C
===============================================================================
> Enter Drive:C

F:\SR>if [C] == [] echo. & echo Invalid User Input  & echo. & pause & goto :TryAgain

F:\SR>if /I C LEQ C If /I C GEQ Z echo. & echo Invalid User Selection  & echo. & pause & goto :TryAgain
& was unexpected at this time.

F:\SR>if /I C geq C & if C leq Z goto :Next1
How can I fix it so I don't get the error.
If there is an easier way to check for a valid drive letter that would be great.

Thank you,

Re: How to ask for input

Posted: 07 Mar 2023 22:41
by ShadowThief
In this particular case, the line

Code: Select all

if /I %Drive% geq C & if %Drive% leq Z goto :Next1
is wrong because you can't chain two if statements together with an ampersand. All you have to do is have them one after the other like you do on the previous line.

On a somewhat related note, it's pretty much always a bad idea to chain commands together using ampersands since it can cause unexpected behavior. It's better to use parentheses and indent things properly so that they're easier to read and debug. Also put quotes around things in case the user enters nothing - this way you prevent a syntax error from causing the script to terminate early.

Code: Select all

@echo off
:TryAgain
cls
::Windows 10 drive
Set "Drive="
echo.
echo ===============================================================================
echo.  Enter the Letter of the drive Windows is on: Example C
echo ===============================================================================
set /p "Drive= > Enter Drive:"
if "%Drive%"=="" (
    echo.
    echo Invalid User Input
    echo.
    pause
    goto :TryAgain
)
if /I "%Drive%" geq "C" (
    if "%Drive%" leq "Z" (
        goto :Next1
    )
)
echo.
echo Invalid User Selection
echo.
pause
goto :TryAgain

:Next1

Re: How to ask for input

Posted: 08 Mar 2023 10:37
by Docfxit
Thank you very much.

That's much clearer.