Set variable in “if” block

2020-08-11 11:04发布

问题:

The following program always echoes "machine-abc" in the end:

@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:

@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?

回答1:

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.

@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%