在批处理文件中使用替换字符串变量的数组进行循环 [英] for loop with array in batch file with replacing a string variable

查看:86
本文介绍了在批处理文件中使用替换字符串变量的数组进行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个批处理文件以通过网络复制文件。

I am trying to create a batch file to copy the file over network.

首先,我使用 NET 命令,然后使用 xcopy 复制文件。

first i am mapping the drive using NETcommand and than copy file using 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

我想替换静态IP '192.168.170.239'并按如下所示配置IP数组,并在循环中替换 netuse 命令。

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.

@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

它适用于第二个ip,但不适用于第一个ip。

It works for the second ip but not for the first 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 
)

这篇关于在批处理文件中使用替换字符串变量的数组进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆