批处理文件无法在 IF 子句中设置变量
即使发生匹配,以下代码也不会将 Run 更新为等于 N。这意味着我不会进入 CALL 代码。我在这里错过了什么吗?
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"
)
)
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"
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用cmd.exe的延迟扩展选项。
在脚本的顶部放置:,
然后
在底部放置:。
那么你需要使用
!Run!
而不是%Run%
。您的代码无法正常工作的原因是,整个 FOR 语句(包括其中的命令)在遇到时都会被评估。这就是
%Run%
变量展开的地方。通过使用延迟扩展,您不会扩展它们,直到实际需要它们(在块中设置它们之后)。
您可以看到此脚本中的差异:
输出:
您会注意到使用
%xx%
进行的检查不起作用,因为在for
语句启动时对其进行了评估(且xx
为 0)。延迟扩展!xx!
确实起作用,因为每次循环都会对其进行评估。You need to use the delayed expansion option of cmd.exe.
At the top of your script, put:
and then put:
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:
which outputs:
You'll notice that the check with
%xx%
does not work because that was evaluated when thefor
statement started (andxx
was 0). The delayed-expansion!xx!
does work since that is evaluated each time through the loop.