12

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

1 Answer 1

22

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%
Sign up to request clarification or add additional context in comments.

4 Comments

Kerrek, This prints "machine-xyz" irrespective of whether the If condition evaluates as true or not?
Sorry, forgot to fix the string comparison. And never mind about then, that was misremembered. Note that the batch processor has no notion of quotation marks delimiting strings, so the quotation marks are just literal characters. You need them, though, to allow for empty variables.
if i drop "THEN" it prints machine-abc; even "IF" the statement evaluates to true. I think we need "THEN"?
I tested this and it works as desired for me now (mind the space after "xyz", I mistyped that earlier). Are you sure that computername is populated correctly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.