21

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!

0

2 Answers 2

18

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
2
  • 3
    wouldn't you have to reference the variable with the !IPAddress! Syntax?
    – cupiqi09
    Commented Aug 11, 2020 at 6:49
  • I concur with @SamDenty. I must use the !varname! syntax when using delayed expansion.
    – Mike Finch
    Commented Jun 12 at 19:16
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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.