我正在尝试编写嵌套在另一个IF ELSE
语句中的IF
语句。这就是我所拥有的:
IF %dirdive%==1 (
IF DEFINED log (
ECHO %DATE%, %TIME% >> %log%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log%
)
GOTO :end
) ELSE (
ECHO %DATE%, %TIME%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2%
)
GOTO :end
)
)
如果未定义log
,我会:
The syntax of the command is incorrect.
ECHO Wed 07/18/2012, 15:50:12.34 >>
Aaaand我不知所措。我试过玩括号。我把最后一个移动到与之前相同的线上并且它不起作用。问题是,当 log
被定义时,可以正常工作。它似乎在IF %dirdive%==1
之后或之后中断,因为它不会在之后插入回显命令。
答案 0 :(得分:15)
问题的根源在于,即使IF语句的分支没有执行,它仍然必须具有有效的语法。
未定义log
时,则为以下行
ECHO %DATE%, %TIME% >> %log%
当log
未定义时,扩展为以下内容
ECHO someDate, someTime >>
重定向后没有文件名,这会导致语法错误。
只要您的log
变量尚未定义括号(当它被定义时),那么只需按如下方式更改该行就可以解决它:
ECHO %DATE%, %TIME% >> "%log%"
当log
未定义
ECHO someDate, someTime >> ""
哪种语法有效。如果执行了“系统无法找到指定的路径”错误,它将失败,但由于日志未定义,它将无法执行: - )
修改强>
或许更好的解决方案是定义一个新变量,当且仅当定义了log
时,该变量才包含值中的重定向运算符。那么你甚至不需要你的大IF语句,代码更容易维护。
SET "redirect="
IF DEFINED log SET "redirect=>>!log!"
IF %dirdive%==1 (
ECHO %DATE%, %TIME% %redirect%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log%
)
GOTO :end
)
请注意,必须在ECHO语句中使用正常扩展%redirect%
。延迟扩展!redirect!
将不起作用,因为命令解析器的重定向阶段发生在延迟扩展之前。
答案 1 :(得分:1)
另一种解决方案是使用GOTO。也许不那么优雅,但很容易理解。
IF %dirdive%==1 (
IF DEFINED log GOTO logdefined ELSE GOTO nolog
)
:logdefined
ECHO %DATE%, %TIME% >> %log%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log%
)
GOTO :end
:nolog
ECHO %DATE%, %TIME%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2%
)
GOTO :end
答案 2 :(得分:0)
将IF DEFINED log
更改为:IF EXIST log
。以下适用于我:
echo off
set log=log.txt
set /p dirdive= Enter a directory:
IF %dirdive%==1 (
IF EXIST %log% (
ECHO "in IF" %DATE%, %TIME% >> %log%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log%
)
GOTO :end
) ELSE (
ECHO "in ELSE" %DATE%, %TIME%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2%
)
GOTO :end
)
)
:end
答案 3 :(得分:0)
****@SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION****
IF %dirdive%==1 (
IF DEFINED log (
ECHO %DATE%, %TIME% >> ****!log!****
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% ****!log!****
)
GOTO :end
) ELSE (
ECHO %DATE%, %TIME%
FOR /R %root1% %%G IN (.) DO (
SET _G=%%G
CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2%
)
GOTO :end
)
)
****@ENDLOCAL****
JoãoMac-Cormick
答案 4 :(得分:-1)
@if not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)ELSE title %random%&set C=1&set D=2&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL&CLS
:Y
color %D%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%
IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&IF %D% EQU 9 (set D=1)ELSE set /A D=%D%+1)ELSE set /A C=%C%+1
goto Y
`