我的批处理“ IF ELSE”示例有什么问题?

时间:2019-08-06 08:43:39

标签: batch-file if-statement

我尝试运行以下代码:

@echo off

IF (%4%=="true") (
     echo "First if" 
     powershell.exe -file "installRgExe2.ps1" %1 %2 %3 [] "true"
)
ELSE (
        IF (%5%=="true") (
            echo "Second if"
            powershell.exe -file "installRgExe2.ps1" %1 %2 %3 %4 "true"
        )
        ELSE (
            echo "Last else" 
            powershell.exe -file "installRgExe2.ps1" %1 %2 %3 %4 "false"
        )
)

我得到了错误:

'ELSE' is not recognized as an internal or external command,
operable program or batch file.
'ELSE' is not recognized as an internal or external command,
operable program or batch file.

由于ELSE错误,将执行ELSE块中的代码,这意味着将打印“其余”。

那么....我的语法有什么问题?:\

2 个答案:

答案 0 :(得分:1)

快速示例,基于提供的注释

@Echo Off
If "%~4" == "true" (
    Echo "First if"
    PowerShell -File ".\installRgExe2.ps1" "%~1" "%~2" "%~3" "[]" "true"
) Else (
    If "%~5" == "true" (
        Echo "Second if"
        PowerShell -File ".\installRgExe2.ps1" "%~1" "%~2" "%~3" "%~4" "true"
    ) Else (
        Echo "Last else"
        PowerShell -File ".\installRgExe2.ps1" "%~1" "%~2" "%~3" "%~4" "false"
    )
)

答案 1 :(得分:1)

if/else块的构造错误,必须确保elseif后面命令序列的右括号(键入{{1} }进入命令提示窗口):

if /?

请注意,条件不能带括号。

然后,您以错误的方式引用command line arguments,没有闭合的if <condition> ( <command sequence> ) else ( <command sequence> ) 符号,因此%%4%是错误的,您必须使用{{ 1}}和%5%。但是,您必须确保比较运算符%4的左右引号是相同的,因为实际上它们也被比较了:

%5

如您所见,我显式地使用了引号,例如==if /I "%~4" == "true" ( echo First if powershell.exe -file "installRgExe2.ps1" "%~1" "%~2" "%~3" "" "true" ) else ( if /I "%~5" == "true" ( echo Second if powershell.exe -file "installRgExe2.ps1" "%~1" "%~2" "%~3" "%~4" "true" ) else ( echo Last else powershell.exe -file "installRgExe2.ps1" "%~1" "%~2" "%~3" "%~4" "false" ) ) "%~4"修饰符会预先从参数中删除潜在的引号,以避免出现超引号。

此处的"%~5"选项用于指定不区分大小写的比较;如果不想的话,将其删除。

相关问题