2013-11-22 46 views
1

如何能够做到以下几点:批处理执行命令环状带连续数组值

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的(远程运行命令)。我想通过循环遍历该函数来缩减代码,并使用主机阵列中的下一个服务器的名称,每次迭代:do_stuff_with_each_host_in_turn

非常感谢!

回答

3

虽然你可以做到这一点使用你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. 

这种方式更容易遵循,作为奖励,您不必在脚本中对主机名进行硬编码。

3

与马克的想法继续,但你不必把主机在一个单独的文件:

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

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

如果你真的想使用你的主机“阵列”,则:

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 
1

您可以处理所有阵列元素,而无需以前对其进行计数:

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



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