22

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

19

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

2 Comments

wouldn't you have to reference the variable with the !IPAddress! Syntax?
I concur with @SamDenty. I must use the !varname! syntax when using delayed expansion.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.