set /p FILEINPUT="1, 2 or 3?"
if "%FILEINPUT%"==("1","2") ( do this command
) else ( do this command )
所以在这个例子中,我希望程序检查用户输入的内容,如果是1或2则执行第一个命令,如果是其他内容则执行第二个命令。我需要在if部分放置什么来检查多个变量?因为这似乎不起作用。
答案 0 :(得分:0)
批处理文件没有逻辑运算符,例如和或,也没有if-else语句。但是,您可以使用嵌套的if语句或“或”变量来实现相同的效果。它需要更多的工作。看一下这篇文章:
答案 1 :(得分:0)
有几种方法(或解决方法,可以随意调用它)来做到这一点,这里有一个:
set _ONEorTWO="12"
set /p FILEINPUT="1, 2 or 3?"
REM Keep only the first character.
set FILEINPUT=%FILEINPUT:~0,1%
CALL set _final=%%_ONEorTWO:%FILEINPUT%=%%
if NOT %_final% == %_ONEorTWO% (
REM answered 1 or 2
echo in if
) else (
echo in else
)
答案 2 :(得分:0)
这是一个FOR
loop可以扩展到几乎任何可接受用户回复的解决方案:
rem remove variable _match
set "_match="
set /p FILEINPUT="1, 2 or 3?"
rem check whether user's reply is in (1 2) set
for %%G in (1 2) do if "%FILEINPUT%"=="%%~G" set "_match=%%~G"
if defined _match (
echo do this command: "if" branch
) else (
echo do this command: "else" branch
)
The link provided说“FOR
有条件地对多个文件执行命令”,但实际上FOR
命令会处理字符串,无论这些字符串表示文件还是不表示。
扩展程序:
脚本:
:again
set "FILEINPUT="
rem remove variable _match
set "_match="
set /p "FILEINPUT=one of main menu items at stackoverflow.com: "
rem format user's reply
rem two-words maximally: remove redundant white spaces
for /F "tokens=1,2*" %%G in ("%FILEINPUT%") Do (
rem echo [%%~G] [%%~H] [%%~I]
if "%%~I"=="" if "%%~H"=="" (
set "FILEINPUT=%%~G"
) else (
set "FILEINPUT=%%~G %%~H"
)
)
rem check whether user's reply is right
for %%G in (
Questions Tags Users Badges Unanswered "Ask Question"
) do (
if /I "%FILEINPUT%"=="%%~G" set "_match=%%~G"
)
if defined _match (
echo "if" branch [%FILEINPUT%]==[%_match%]
goto :next
) else (
echo "else" branch [%FILEINPUT%]
if not "%FILEINPUT%"=="" goto :again
)
:next
输出:
==>28886458.bat
one of main menu items at stackoverflow.com: ask questiO N
"else" branch [ ask questiO N ]
one of main menu items at stackoverflow.com: ask questiON
"if" branch [ask questiON]==[Ask Question]
==>28886458.bat
one of main menu items at stackoverflow.com: TAGGS
"else" branch [TAGGS]
one of main menu items at stackoverflow.com: TAGS
"if" branch [TAGS]==[Tags]
答案 3 :(得分:0)
以下是使用(更好)choice
命令与goto
结合使用的另一种方式:
choice /C 123 /N /M "1, 2 or 3?"
set input=%errorlevel%
if %input%==0 goto end
goto %errorlevel%
:1
:2
Echo You pressed 1 or 2
goto end
:3
Echo You pressed 3
goto end
.....
:end
Echo End of Program
Pause