Arrays 批处理使用连续数组值执行循环命令

Arrays 批处理使用连续数组值执行循环命令,arrays,batch-file,iteration,Arrays,Batch File,Iteration,我如何实现以下目标: 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 targetho

我如何实现以下目标:

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
我的上下文实际上是在一长串服务器上执行一系列PSexec(远程运行命令)。我希望通过循环函数来精简代码,并在每次迭代时使用主机阵列中的下一台服务器的名称:dou-stuff\u-with\u-each\u-host\u


非常感谢

虽然您可以使用随
set/a
递增的索引变量来执行此操作,但我认为您会发现将服务器列表保存在文本文件中更有用,然后执行以下操作:

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.

这种方法更容易理解,而且作为一种奖励,您不必在脚本中硬编码主机名。

虽然您可以使用随
set/a
递增的索引变量来实现这一点,但我认为您会发现将服务器列表保存在文本文件中更有用,然后执行以下操作:

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.

这种方法更容易理解,而且作为奖励,您不必在脚本中硬编码主机名。

继续马克的想法,除非您不必将主机放在单独的文件中:

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

:do_stuff
ping %1
do stuff involving %1
exit /b
如果确实要使用主机“阵列”,则:


继续马克的想法,除非你不必把主机放在一个单独的文件中:

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

:do_stuff
ping %1
do stuff involving %1
exit /b
如果确实要使用主机“阵列”,则:


您可以通过以下方式处理所有数组元素,而无需事先对其进行计数:

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



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

您可以通过以下方式处理所有数组元素,而无需事先对其进行计数:

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



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