Windows批处理变量将不会设置 [英] Windows Batch Variables Won't Set
问题描述
我觉得我遇到了一个错误在窗口的批处理脚本。
I think I ran into a bug in Window's batch scripting.
我无法设置是在扩展if语句的变量。
I cannot set variables that are in an expanded if statement.
下面是我的脚本的一个孤立的部分:
Here is an isolated part of my script:
@echo off
set success=1
set Version=12345
set Target=Client
set Type=456
set dir=
set zip=
if "%Version%"=="" set success=0
if "%Type%"=="" set success=0
if 1==1 set test=42
if %success%==1 (
set test2=57005
if "%Target%"=="Client" (
set dir=ModName v%Version%
set zip=ModName v%Version% %Type%.zip
echo Version: %Version%
echo Type: %Type%
echo.
echo Target: %Target%
echo dir: %dir%
echo zip: %zip%
echo.
echo test: %test%
echo test2: %test2%
)
) else (
echo Not successful.
)
这是从CMD的一个全新的实例的输出:
This is the output from a brand new instance of cmd:
C:\Users\RandomClown\Desktop>test.bat
Version: 12345
Type: 456
Target: Client
dir:
zip:
test: 42
test2:
你应该注意到的是,单行if语句设置正确的东西。
如果将执行什么,是不是一套多行。我不认为我错过了什么。
另外,如果语句执行正确的行权,因为其他多行(回波没有成功。)
行未执行。
为什么行没有执行?
推荐答案
您错过了什么; - )
You missed something ;-)
CMD
扩展变量时,命令的解析</ em>的,而不是当它们运行。事实上,有一个如果
或为
语句块(...)
(或实际上任何块)counds在这种情况下一个命令。所以,当你设置一个块中变量的和的尝试在同一块使用它们没有变量了 - 他们是由变量有值替换的前的块甚至被处决
cmd
expands variables when commands are parsed, not when they are run. It so happens that an if
or for
statement with a block ( ... )
(or actually any block) counds as a single command in that case. So when you set variables inside a block and try using them in the same block there are no variables anymore – they were replaced by the values the variables had before the block even executed.
贴
setlocal enabledelayedexpansion
在您的批处理文件的开头,并使用!拉链!
而不是的拉链%%
。参见帮助集
对这个问题的详细讨论。
at the start of your batch file and use !zip!
instead of %zip%
. See help set
for a detailed discussion of the problem.
这篇关于Windows批处理变量将不会设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!