【问题标题】:Errorlevel with choice in batch files executes wrong cases批处理文件中选择的错误级别执行错误的情况
【发布时间】:2021-07-18 20:32:26
【问题描述】:

谁能告诉我如何让errorlevel 停止取值1 或更大?我希望它只考虑确切的值。如果我选择 2,我希望它采用第二个选项。 现在,如果我选择“1”,它将执行 DLL 文件而不是 LOG 的选项。我尝试了不同的版本,例如: 如果错误级别为 1,尝试将括号与 else 等一起使用,但它们都不起作用。这段代码有什么问题?

@echo off
cls
choice /C 12 /M "dll or log?"

if %errorlevel%=="2" dir %1\*.dll >> %2.txt
echo DLL
goto end
if %errorlevel%=="1" dir %1\*.log >> %3.txt
echo LOG
goto end
:end
exit /b

【问题讨论】:

  • 引号是比较的一部分,因此必须在两边都出现或没有......

标签: if-statement batch-file cmd errorlevel


【解决方案1】:

这个决议:

@echo off
cls
rem choice /C 12 /M "dll or log?"
choice /C 12 /M "log or dll?"

if %errorlevel%==2 (dir %1\*.dll >> %2.txt
echo DLL
goto end)
if %errorlevel%==1 (dir %1\*.log >> %3.txt
echo LOG
goto end)
:end
exit /b

您需要使用“(”“)”来控制流程,并且不需要错误级别编号周围的"


奖金

这是一种更灵活的替代方法:

@echo off

if "%~3"=="" echo lack of parameters & goto :EOF

cls
choice /C 12 /M "log or dll?"
Goto Choice%ErrorLevel%

:Choice2
  dir "%~1\*.dll" >> "%~2.txt"
  echo DLL in %~1
goto end

:Choice1
  dir "%~1\*.log" >> "%~3.txt"
  echo LOG in %~1
goto end

:end
exit /b

参数中的~去掉eventual sorround双引号。那么加引号的surrond可以防止参数里面有空格。

【讨论】:

    【解决方案2】:

    ERRORLEVEL 值始终为数字。可以使用“比较操作”。请参阅IF /? 了解更多信息。

    如果路径中有空格或其他特殊字符,则需要引用文件系统路径。正如@Gerhard 所述,在 "%~3" 中使用 TILDE 会删除 %3 参数周围的所有现有引号字符。

    顺便说一句,此脚本不会检查 %1、%2% 或 %3 是否具有任何实际值或它具有的值是否可用。

    @echo off
    cls
    SETLOCAL ENABLEEXTENSIONS
    choice /C 12 /M "dll or log?"
    
    if %errorlevel% EQU 2 (
        dir "%~1\*.dll" >> "%~2.txt"
        echo DLL
        goto end
    )
    if %errorlevel% EQU  1 (
        dir "%~1\*.log" >> "%~3.txt"
        echo LOG
        goto end
    )
    
    :end
    exit /b
    

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多