批处理文件未能设置变量,IF子句 [英] batch file fails to set variable in IF clause
问题描述
以下code未更新运行等于N为偶数虽然匹配发生。这意味着我没有落入CALL code。我思念的东西在这里?
SET运行= YREM检查当前的文件日期/时间信息,并确定是否该文件已被present太长目录
REM跳过前4行作为标题信息不要求FOR / F令牌= 1-5 =跳过4 delims =%% G IN('DIR / OD%SRCH_CRITERIA%')DO( ECHOPARAMS到processFile:%%摹%% ^ h %%我%% K
IF %%ķ==。 (
ECHOK:没有什么
集中运行= N
ECHO%运行%
) IF %%满足K ==免费(
ECHOK:FREE
集中运行= N
ECHO%运行%
) ECHO%运行RUN%
IF%运行%==Y(
CALL:processFile%% G%% H我%%%% K
)
)
您需要使用CMD.EXE的延迟扩展选项。
在你的脚本的顶部,放:
SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion
然后放:
ENDLOCAL
在底部。
然后,你需要使用!快跑!
而不是%运行%
。
您code未工作的原因是,全部的FOR语句(包括其中的命令)的遭遇,当它被评估。这就是地步%运行%
变量被扩展。
通过使用扩展推迟,你不展开它们,直到他们真正需要(你块中设置后,它们)。
您可以看到这个脚本的区别是:
关闭@echo
SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion设置XX = 0
为%%我在(A B C D)做(
回声%%我
集/一个XX = XX + 1
如果%XX%== 3回声是正常的
如果!XX!== 3回声是为延迟
)ENDLOCAL
它输出:
A
b
C
是为延迟
ð
您会发现,与%XX%
检查不起作用,因为这是评估当为
声明开始(和 XX
为0)。延迟膨胀!XX!
的确实的,因为这项工作是通过每次循环评估。
The following code is not updating Run to equal N even though the match occurs. this means I'm not dropping into the CALL code. Am i missing something here?
SET Run=Y
REM Check current files date/time information and establish if the file has been present too long in the directory
REM Skip first 4 lines as header information not required
FOR /f "tokens=1-5 skip=4 delims= " %%G IN ('dir /OD "%SRCH_CRITERIA% "') DO (
ECHO "Params to processFile: " %%G %%H %%I ""%%K""
IF %%K.==. (
ECHO "K:nothing"
SET Run=N
ECHO %Run%
)
IF %%K==free (
ECHO "K:FREE"
SET Run=N
ECHO %Run%
)
ECHO %Run% RUN
IF %Run%=="Y" (
CALL :processFile "%%G" "%%H" "%%I" "%%K"
)
)
You need to use the delayed expansion option of cmd.exe.
At the top of your script, put:
setlocal enableextensions enabledelayedexpansion
and then put:
endlocal
at the bottom.
Then you need to use !Run!
instead of %Run%
.
The reason your code is not working is that the entire FOR statement (including the commands within it) is evaluated when it's encountered. That's the point where the %Run%
variables are expanded.
By using deferred expansion, you don't expand them until they're actually needed (after you've set them within the block).
You can see the difference in this script:
@echo off
setlocal enableextensions enabledelayedexpansion
set xx=0
for %%i in (a b c d) do (
echo %%i
set /a "xx = xx + 1"
if %xx%==3 echo yes for normal
if !xx!==3 echo yes for delayed
)
endlocal
which outputs:
a
b
c
yes for delayed
d
You'll notice that the check with %xx%
does not work because that was evaluated when the for
statement started (and xx
was 0). The delayed-expansion !xx!
does work since that is evaluated each time through the loop.
这篇关于批处理文件未能设置变量,IF子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!