如何在批处理文件中写入IF和ELSE

问题描述 投票:0回答:1
@ECHO OFF
SETLOCAL EnableDelayedExpansion


SET /P tool=Please enter the tool name: 

If %tool%=="fw-test.exe" (echo "The tool name is fw-test.exe") else (echo "Unknown tool name") 

If %tool%=="ick-test.exe" (echo "The tool name is ick-test.exe") else (echo "Unknown tool name")

我收到语法错误。我应该如何写才能正常工作?

batch-file if-statement
1个回答
0
投票

[您不应该做两个单独的if语句,一个应该在else语句中包含另一个,否则,您将同时获得结果tool name.exeunknown tool name,因为如果匹配第一个而不是第二个:] >

@echo off
set /p tool=Please enter the tool name: 

If /i "%tool%"=="fw-test.exe" (
      echo "The tool name is fw-test.exe"
    ) else (
      If /i "%tool%"=="ick-test.exe" (
      echo "The tool name is ick-test.exe"
    ) else (
      echo Unknown Tool
  )
)

注意

我正在用双引号评估==的两侧。否则,您将永远不会获得比赛。这是错误的:if var=="var",因为没有引用:if "var"=="var"完全匹配。我包括/I选项,它也允许将名称键入为FW-TEST.exe以及大小写混合的形式。

但是,如果您仅计划使用选定的预定义工具,则只需使用choice,它将允许用户仅选择以下两种工具之一:

@echo off

echo 1. fw-test.exe
echo 2. ick-test.exe
choice /c 12 /m "Select a tool"
goto tool%errorlevel%
:tool1
echo you chose option %errorlevel% fw-test.exe
goto eof
:tool2
echo you chose option %errorlevel% ick-test.exe
© www.soinside.com 2019 - 2024. All rights reserved.