2013-11-22 96 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