簡體   English   中英

用批處理文件中的數組替換字符串變量進行循環

[英]for loop with array in batch file with replacing a string variable

我正在嘗試創建一個批處理文件以通過網絡復制該文件。

首先,我使用NET命令映射驅動器,然后使用xcopy復制文件。

跟隨批處理文件可以正常工作

    net use T: \\192.168.170.239\D /user:User1 PASSWROD
    set source=T:\backup
    set destination=D:\backup\
    xcopy %source% %destination% /y
    net use T: /delete 
    TIMEOUT 5

我想替換靜態'192.168.170.239'並制作如下所示的任何IP數組,並在循環中替換netuse命令。

@echo off 
set obj[0]=192.168.170.239
set obj[1]=192.168.170.240
set obj[2]=192.168.170.241
set obj[3]=192.168.170.242

我已經整理了以下內容,但沒有起作用

 @echo off
set len=2
set obj[0]=192.168.170.239
set obj[1]=192.168.170.240


set i=0
:loop
if %i% equ %len% goto :eof
for /f "usebackq delims== tokens=2" %%j in (`set obj[%i%]`) do (

net use T: \\%%j\D /user:User1 Password
TIMEOUT 10
set source=T:\Autobackup
set destination=D:\Autobackup\
xcopy %source% %destination% /y
net use T: /delete 
TIMEOUT 10

)
set /a i=%i%+1
goto loop

它適用於第二個IP,但不適用於第一個IP。

您實際上應該在看一個更像這樣的結構:

@Echo Off

Rem Undefine any existing variables beginning with obj[
For /F "Delims==" %%A In ('Set obj[ 2^>Nul') Do Set "%%A=" 

Rem Define your IP list
Set "obj[0]=192.168.170.239"
Set "obj[1]=192.168.170.240"
Set "obj[2]=192.168.170.241"
Set "obj[3]=192.168.170.242"

Rem Define your Map Source and Destination
Set "map=T:"
Set "source=%map%\Autobackup"
Set "destination=D:\Autobackup\"

Rem Loop through the IP list
For /F "Tokens=1* Delims==" %%A In ('Set obj[ 2^>Nul') Do (

    Rem Make sure that %map% is not currently mapped
    Net Use %map% /Delete 2>Nul

    Rem Map the share
    Net Use %map% \\%%B\D /User:User1 Password

    Rem Perform the required operation
    XCopy "%source%" "%destination%" /Y

    Rem Delete the mapped share
    Net Use %map% /Delete 
)

Compo的答案很好。 下面是構造循環的另一種方法。 它不使用變量的“數組”。 我發現這更容易編輯和理解。

SET IPLIST=^
192.168.170.239 ^
192.168.170.240 ^
192.168.170.241 ^
192.168.170.242

FOR %%a IN (%IPLIST%) DO (
    ECHO %%a
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM