19

I'm trying to make a batch file that will check your computer's name, and then it will set your IP address to the corresponding IP address for that computer.

I have a variable called IPAddress that stores the new IP address. Then I have an IF statement to check the computer name and assign the new IP address. My problem is that inside the IF statement, when I set the IPAddress variable to the new IP I want, it doesn't stick. When I try echoing the IPAddress variable right after I set it, it's still the original state.

Here's my code:

@echo off

SET IPAddress=192.168.1.1

IF %computername%==TEST (
    ECHO "TEST" computer
    SET IPAddress=192.168.1.50
    ECHO New IP Address: %IPAddress%
) ELSE IF %computername%==BRIDGE (
    ECHO "BRIDGE" Computer
    SET IPAddress=192.168.1.25
    ECHO New IP Address: %IPAddress%
)

pause

I am on the "BRIDGE" computer and I get this output:

"BRIDGE" Computer
New IP Address: 192.168.1.1
Press any key to continue . . .

I can't understand why the SET statement inside the IF statement doesn't seem to be working.

Any ideas?

Thanks in advance!

Jyclop
  • 469
  • 1
  • 6
  • 15
  • 2
    Read one of the thousands questions/answers with `delayed expansion` referring to (code blocks) in parentheses where cmd.exe evaluates the vars when entering the block. To get actual values you need to force delayed expansion. –  Feb 16 '17 at 20:45

2 Answers2

14

You can either use delayed expansion, or simplify your script to call an external label which isn't bound to the limitations of the current expansion.

Simplified script:

@echo off
SET "IPAddress=192.168.1.1"
IF "%computername%"=="TEST" (call :IPAddress "TEST" "192.168.1.50") else (IF "%computername%"=="BRIDGE" (call :IPAddress "BRIDGE" "192.168.1.25"))
pause
exit

:IPAddress
    ECHO "%~1" computer
    SET "IPAddress=%~2"
    ECHO New IP Address: %IPAddress%
goto :EOF

Old script with delayed expansion:

@echo off
setlocal ENABLEDELAYEDEXPANSION

SET IPAddress=192.168.1.1

IF %computername%==TEST (
    ECHO "TEST" computer
    SET IPAddress=192.168.1.50
    ECHO New IP Address: %IPAddress%
) ELSE IF %computername%==BRIDGE (
    ECHO "BRIDGE" Computer
    SET IPAddress=192.168.1.25
    ECHO New IP Address: %IPAddress%
)

pause
Community
  • 1
  • 1
Sam Denty
  • 3,693
  • 3
  • 30
  • 43
5
@echo off

SET IPAddress=192.168.1.1

IF %computername%==TEST (
    ECHO "TEST" computer
    SET IPAddress=192.168.1.50
) ELSE IF %computername%==BRIDGE (
    ECHO "BRIDGE" Computer
    SET IPAddress=192.168.1.25
)

ECHO New IP Address: %IPAddress%

pause

As already pointed, your original code needs delayed expansion, or just to move the echo out of the if block

MC ND
  • 69,615
  • 8
  • 84
  • 126