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!
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
So %%k refers to the value of the 3rd token, which is what is returned.
One of the common uses for the 'if' statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the 'if' statement can be done for both strings and numbers.
%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With