1

How can I achieve the following:

set host[0]=\\thisserver
set host[1]=\\thatserver
set host[2]=\\otherserver

set targethost = host[0]


call :do_stuff_with_each_host_in_turn


:do_stuff_with_each_host_in_turn
ping %targethost%
do stuff involving %targethost%
set targethost=%host%[next]
call :do_stuff_with_each_host_in_turn
popd 
EXIT /B

My context is actually to carry out a series of PSexec (running commands remotely) on a long list of servers. I'd like to slim down the code by looping through the function and just use the name of the next server from the host array with each iteration of :do_stuff_with_each_host_in_turn

Many thanks!

3 Answers 3

3

Continuing with Mark's idea, except you don't have to put the hosts in a separate file:

for %%H in (
  \\thisserver
  \\thatserver
  \\otherserver
) do call :do_stuff %%H
exit /b

:do_stuff
ping %1
do stuff involving %1
exit /b

If you really want to use your host "array", then:

set host[1]=\\thisserver
set host[2]=\\thatserver
set host[3]=\\otherserver
set hostCount=3

for /l %%N in (1 1 %hostCount%) do call :do_stuff %%host[%%N]%%
exit /b

:do_stuff
ping %1
do stuff involving %1
exit /b
Sign up to request clarification or add additional context in comments.

Comments

3

While you can do that using an index variable that you increment with set /a, I think you'll find it much more useful to keep your list of servers in a text file, then do something like this:

set SERVERLIST=servers.txt
for /f %%x in (%SERVERLIST%) do call :do_stuff_with_each_host_in_turn %%x
echo Script is done...
exit /b

:do_stuff_with_each_host_in_turn
REM %1 is the value you passed in from your for loop
set SERVER=%1
REM psexec \\%SERVER% -u user -p password etc., etc.

This way is a little easier to follow, and as a bonus, you won't have to hardcode your host names in your script.

Comments

1

You can process all array elements with no need of previously count them this way:

for /F "tokens=1* delims==" %%a in ('set host[') do call :do_stuff %%b



:do_stuff
ping %1
do stuff involving %1
exit /b

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.