When I first started trying to build this, as a way of keeping an external file holding variables for IP addresses so I only ever had to edit one list, I felt I was doing something wrong. But then it worked. However it also outputted The system cannot find the drive specified
in between the 'IP' and 'Name'. this stopped when I changed ::
to rem
, (code updated)
I aim to base a lot of automatic deployment and maintenance off of this, in calls to servers e.g. pscp/ plink (PuTTY) and in writing to log files to say e.g. Deploying on [name] xxxx
. Is this a robust/appropriate way of writing this code? It feels strangely clean to me.
Can I check: is using the !xxx!
making use of the delayed expansion? If so, should you always wrap variables in !
for delayed expansion? (I read Windows Batch files: what is variable expansion, and what does EnableDelayedExpansion mean? but it's not 100% clear to me that it's the !
which is causing this.)
What is this called? Am I using a variable value as the name of the variable and is there a computer science phrase for this? Is it an eval?
@echo off
setlocal EnableDelayedExpansion
set ips[0]=192.168.0.1
set 192.168.0.1=router
set ips[1]=192.168.0.2
set 192.168.0.2=printer
set ips[2]=192.168.0.3
set 192.168.0.3=nas
for /F "tokens=2 delims==" %%a in ('set ips[') do (
rem the next line outputs the IP as it is evaluating the dynamic
rem variable being temp created with the for loop
echo IP is %%a
rem with delayed expansion set (see top) we can use the value
rem of the IP that is being used with the for loop
rem and further lookup by essentially evaluating again
echo Name of IP is !%%a!
)
pause
RESULT:
IP is 192.168.0.1
Name of IP is router
IP is 192.168.0.2
Name of IP is printer
IP is 192.168.0.3
Name of IP is nas
Press any key to continue . . .
Putting IP array into external file
So continuing with the edited code (edits reflected above), I now try to move the IP array into an external file and call it in, and it gives Environment variable ips[ not defined
demo.bat:
@echo off
setlocal EnableDelayedExpansion
call info_IPs.bat
for /F "tokens=2 delims==" %%a in ('set ips[') do (
rem the next line outputs the IP as it is evaluating the dynamic
rem variable being temp created with the for loop
echo IP is %%a
rem with delayed expansion set (see top) we can use the value
rem of the IP that is being used with the for loop
rem and further lookup by essentially evaluating again
echo Name of IP is !%%a!
)
pause
info_IPs.bat:
@echo off
setlocal EnableDelayedExpansion
set ips[0]=192.168.0.1
set 192.168.0.1=router
set ips[1]=192.168.0.2
set 192.168.0.2=printer
set ips[2]=192.168.0.3
set 192.168.0.3=nas