执行批处理文件时,IF条件下该命令的语法不正确

时间:2014-08-27 13:46:05

标签: batch-file

在下面的代码我得到的命令的语法是错误的错误。最有可能在第一个IF声明中。但有时它运作顺利。不知道为什么?请帮忙

@ECHO OFF
IF "%~1" == "" (
    ECHO Please provide file location
    GOTO End
) ELSE (
    echo %1
    SET FILE=%1
    IF NOT EXIST %FILE% (
        ECHO Invalid File. Please provide correct path of file.
        GOTO End
    )
    echo file found
)
:End
echo End of script

1 个答案:

答案 0 :(得分:2)

@ECHO OFF
setlocal enableDelayedExpansion
IF "%~1" == "" (
    ECHO Please provide file location
    GOTO End
) ELSE (
    echo %1
    SET "FILE=%~1"
    IF NOT EXIST "!FILE!" (
        ECHO Invalid File. Please provide correct path of file.
        GOTO End
    )
    echo file found
)
:End
echo End of script
endlocal

在括号内设置变量时需要延迟扩展。变量保持未定义,直到括号末尾和cmd解析器看到:

   IF NOT EXIST  (
            ECHO Invalid File. Please provide correct path of file.
            GOTO End
        )

这是在if执行之前检测到的语法错误。

link1 link2