I am trying to use batch scripting to create and assign variables dynamically based on a space separated list of computer names.
The computer names are assigned to %hosts% (which are pulled from another file in the production script). What I am trying to accomplish is to count the number of hosts that were pulled in (they are separated by spaces), then assign each one to a variable that contains a number relating to the order the hosts are listed.
Here is the code snippet:
@echo off
setlocal EnableDelayedExpansion
SET hosts=10.10.0.0 192.168.0.0 W2K3-Server
SET /a counter=0
FOR %%I IN (%hosts%) DO (
SET /a counter+=1
)
echo Total= !counter!
FOR /L %%A IN (1,1,!counter!) DO (
FOR %%I in (%hosts%) DO (
IF [!host%%A!]==[] SET host%%A=%%I
echo host%%A= !host%%A!
)
)
endlocal
The output of this script is:
Total= 3
host1= 10.10.0.0
host1= 10.10.0.0
host1= 10.10.0.0
host2= 10.10.0.0
host2= 10.10.0.0
host2= 10.10.0.0
host3= 10.10.0.0
host3= 10.10.0.0
host3= 10.10.0.0
The results I would like to see is:
Total= 3
host1= 10.10.0.0
host2= 192.168.0.0
host3= W2K3-Server
I know why I am getting the first result. There is no checking to see if a condition is met. In this case, the condition would be setting one of the hosts as a variable. I need to know how to step out of the “FOR %%I in (%hosts%)” section of the loop once a variable has been set.
Is this possible in batch? This piece is not critical to the project I am working on, but it would add value by opening up some new possibilities in other areas of the script.
Like this?