批处理文件未能在 IF 子句中设置变量 [英] batch file fails to set variable in IF clause
问题描述
即使发生匹配,以下代码也不会将 Run 更新为等于 N.这意味着我不会进入 CALL 代码.我在这里错过了什么吗?
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"
)
)
推荐答案
需要使用cmd.exe的延迟扩展选项.
You need to use the delayed expansion option of cmd.exe.
在脚本的顶部,输入:
setlocal enableextensions enabledelayedexpansion
然后放:
endlocal
在底部.
那么你需要使用 !Run!
而不是 %Run%
.
Then you need to use !Run!
instead of %Run%
.
您的代码不起作用的原因是 整个 FOR 语句(包括其中的命令)在遇到时被评估.这就是 %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
哪个输出:
a
b
c
yes for delayed
d
您会注意到使用 %xx%
的检查不起作用,因为在 for
语句开始时(和 xx
为 0).延迟扩展 !xx!
确实 工作,因为每次循环都会对其进行评估.
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屋!