简体   繁体   English

用批处理文件中的数组替换字符串变量进行循环

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

I am trying to create a batch file to copy the file over network. 我正在尝试创建一个批处理文件以通过网络复制该文件。

first i am mapping the drive using NET command and than copy file using xcopy . 首先,我使用NET命令映射驱动器,然后使用xcopy复制文件。

follwing batch file works without any problem 跟随批处理文件可以正常工作

    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

I would like to replace the static IP '192.168.170.239' and make any array of ip as below and replace the netuse command in a loop. 我想替换静态'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

I have treid the following but didn't work 我已经整理了以下内容,但没有起作用

 @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

It works for the second ip but not for the first ip. 它适用于第二个IP,但不适用于第一个IP。

You should really be looking at a structure more like this: 您实际上应该在看一个更像这样的结构:

@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's answer is good. Compo的答案很好。 Another way to construct the loop follows. 下面是构造循环的另一种方法。 It does not use an "array" of variables. 它不使用变量的“数组”。 I find this easier to edit and understand. 我发现这更容易编辑和理解。

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