使用用户输入的控制函数调用:批处理



我想编写一个批处理文件,该文件根据从用户收到的输入工作,但在我的代码上,它总是调用"AddingFile"函数。

@ECHO off
ECHO Select [A] Adding File [R] Remove File [C] Copy File [E] Close Program.
GOTO:startCompile

:startCompile
::CLS
SET /p select = Make a selection. 
IF "%select%"=="1" ( goto addingFileObject )
IF "%select%"=="2" ( goto removeFileObject )
IF "%select%"=="3" ( goto copy )
IF "%select%"=="4" ( goto defaultExit )
:addingFile
ECHO "Adding files"
goto:EOF
:removeFile
ECHO "Remove files"
goto:EOF
:defaultExit
pause
goto:EOF
:copy
ECHO "Copying Filed"
goto:EOF

...并使用更合适的Choice命令:

@Echo Off
Choice /C ARCE /N /M "Select [A]dd [R]emove [C]opy or [E]xit"
If ErrorLevel 4 GoTo :EOF
If ErrorLevel 3 GoTo copy
If ErrorLevel 2 GoTo removeFile
Echo "Adding files"
Timeout 2 /NoBreak>Nul
Exit /B
:removeFile
Echo "Remove files"
Timeout 2 /NoBreak>Nul
Exit /B
:copy
Echo "Copying Files"
Timeout 2 /NoBreak>Nul

代码包含两个错误。

SET /P select<space>=...行是错误的,或者至少会产生意外的行为。
它设置一个名为select<space>的变量,因此通过%select%访问将始终失败。

IF命令块之后缺少exit /bgoto :eof,当没有任何 IF 比较为真时,这会导致不正确的行为。
然后添加文件部分将被执行。

顺便说一句。此类问题可以简单地用ECHO ON进行调试。 在这种情况下,它将通过这些行显示第二个问题,%select%始终为空

...
c:Temp>IF "" == "1" (goto addingFileObject  )
c:Temp>IF "" == "2" (goto removeFileObject  )
c:Temp>IF "" == "3" (goto copy  )
c:Temp>IF "" == "4" (goto defaultExit  )

最新更新