windows 在“if”块中设置变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7805510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set variable in "if" block
提问by nmdr
The following program always echoes "machine-abc" in the end:
以下程序最后总是回显“machine-abc”:
@echo Off
set dropLoc=machine-abc
IF %computername% == "xyz" (
%dropLoc% = machine-xyz
)
echo %dropLoc%
Is this a scope issue? Does the dropLoc variable in the if statement have a different scope? I have tried the following to address the issue:
这是范围问题吗?if 语句中的 dropLoc 变量是否具有不同的作用域?我尝试了以下方法来解决这个问题:
@echo Off
set dropLoc=machine-abc
IF %computername% == "xyz" (
!dropLoc! = machine-xyz
)
echo %dropLoc%
and
和
@echo Off
set dropLoc=machine-abc
IF %computername% == "xyz" (
set dropLoc = machine-xyz
)
echo %dropLoc%
How do I make this work?
我如何使这项工作?
回答by Kerrek SB
You got the SET
syntax right the first time, how come you decided to write something else the second time round? Also, you have to add the quotation marks on both sides of the comparison. Unlike in other script interpreters, quotation marks aren't special for the batch interpreter.
你SET
第一次语法就对了,为什么你决定第二次写其他东西?此外,您必须在比较的两侧添加引号。与其他脚本解释器不同,引号对于批处理解释器来说并不特殊。
@echo off
rem Change this for testing, remove for production
set computername=xyz
set dropLoc=machine-abc
if "%computername%" == "xyz" (
set dropLoc=machine-xyz
)
echo %dropLoc%