SirAleXbox
SirAleXbox

Reputation: 121

Loop robocopy through network drives

EDIT: If anyone cares here's a working version of my original code. Only by removing the space in the "Drive C" path I could get robocopy to take the /r:1 /w:1 options. I'm aware now, is in no way the best way to do it.

@echo off
setlocal enabledelayedexpansion
set "count=1"
set "local=c:\cmd_Scripts\"

:update
echo Connecting to machine !count!.
if exist "\\10.3.71.6!count!\Disk_C\cmd_Scripts\" (
    robocopy %local% \\10.3.71.6!count!\Disk_C\cmd_Scripts\ /r:1 /w:1
    echo Machine !count! DONE.
    echo.
    set /a count+=1
    if /i !count! LEQ 9 goto update
) else (
    echo MAchine !count! not available.
    echo.
    set /a count+=1
    if /i !count! LEQ 9 goto update
)

So again I'm stuck. If the network drive is available works fine, but if not available should go to the next IP. Also I don't understand why need to open "%target% but can't close ". And because of this can't pass any options like /r:1 /:w1

@echo off
set count=1
set "local=c:\cmd_Scripts\"
set "target=\\10.3.71.6%count%\Disk C\cmd_Scripts\"

:update
if exist %target% (
    set "target=\\10.3.71.6%count%\Disk C\cmd_Scripts\"
    robocopy %local% "%target%
    set /a count+=1
    if /i %count% LEQ 9 goto update
) else (
    set /a count+=1
    if /i %count% LEQ 9 goto update
)   
pause

Thanks Alex

Upvotes: 0

Views: 292

Answers (2)

user7818749
user7818749

Reputation:

Maybe move away from the count and use for /l instead.

@echo off
set "local=c:\cmd_Scripts\"
for /l %%i in (1,1,9) do (
if exist "\\10.3.71.6%%i\Disk C\cmd_scripts\" robocopy "%local%" "\\10.3.71.6%%i\Disk C\cmd_scripts\"
)

if you really need to set the target variable:

@echo off
Setlocal enabledelayedexpansion
set "local=c:\cmd_Scripts\"
for /l %%i in (1,1,9) do (
set "target=\\10.3.71.6%%i\Disk C\cmd_scripts\"
if exist "!target!" robocopy "!local!" "!target!"
)

From cmdline, do for /? to understand what it does, especially with the /l switch. but in short doing (1,1,9) means we count from 1, in 1s to 9 and perform the parenthesized commands 9 times in this case.

Upvotes: 1

Compo
Compo

Reputation: 38614

I would probably write it like this:

@Echo Off
Set "DLocal=C:\cmd_Scripts"
Set "IPBase=\\10.3.71.6"

For /L %%A In (1 1 9) Do If Exist "%IPBase%%%A\Disk %DLocal::=%\" (
    RoboCopy "%DLocal%" "%IPBase%%%A\Disk %DLocal::=%" /<options>
)
Pause

Edit

What follows is effectively a repeat of my answer but with more similarity to your question code. It means that you can preset %target% and use it in your loop, without enabling delayed expansion.

@Echo Off
Set "local=C:\cmd_Scripts"
Set "target=\\10.3.71.6%%A\Disk %local::=%"

For /L %%A In (1 1 9) Do (
    Echo %target%
    If Exist "%target%\" RoboCopy "%local%" "%target%" /<options>
)
Pause

Upvotes: 1

Related Questions