代码之家  ›  专栏  ›  技术社区  ›  Tarun. P

替换字符串变量的批处理文件中带数组的for循环

  •  0
  • Tarun. P  · 技术社区  · 6 年前

    我正在尝试创建批处理文件以通过网络复制该文件。

    首先,我使用 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
    

    我想更换静态IP '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。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Compo    6 年前

    你真的应该看一个更像这样的结构:

    @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 
    )
    
        2
  •  0
  •   lit    6 年前

    康波的回答很好。另一种构造循环的方法如下。它不使用变量的“数组”。我觉得这更容易编辑和理解。

    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
    )