Alexander Piel
Alexander Piel

Reputation: 21

Multiple For Loops in Batch Script on same Content

I set up a batch (copy.bat) file in my Windows sendto Directory that is for Copying a bunch of files via rightclicking the directories and choosing sendto "copy.bat".

@echo off
setlocal enabledelayedexpansion

set cnt=0
set cur=0

:files
for /R "%~1" %%F in (*.7z, *.avi) do (set /a cnt+=1)
shift
if "%~1" NEQ "" goto :files
echo !cnt! files found for copying.

echo Processing ...


set "DEST_DIR=E:\"
:while
for /R "%~1" %%F IN (*.7z, *.avi) do (
    if exist "%%F" (
        set FILE_DIR=%%~dpF
    set FILE_INTERMEDIATE_DIR=!%%~dpF:%%~1%=!
        xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
    )
    set /a cur+=1
    echo !cur!/!cnt! done...
)
shift
if "%~1" NEQ "" goto :while

pause

If I run the first for loop alone it counts the files. If I run the second loop on its own it copies exatly those files the other loop is supposed to count. However, both loops in one batch file will somehowe conflict. The Filecount works correctly but the copy process delivers an error: "The Path of is too long". Between "of" and "is" there is an additional Space. The final pause will correctly wait for button press. I assume it has to do something with the %%F variable, but renaming it in one of the loops does not help.

Upvotes: 0

Views: 99

Answers (1)

Magoo
Magoo

Reputation: 80203

Please change the name of your .bat - copy is a keyword to cmd.

Your problem is that the first routine shifts out all of the parameters, so your second routine has no parameters to deal with.

The easiest way is probably:

set "DEST_DIR=E:\"
call :while %*
pause
goto :eof

:while
for /R "%~1" %%F IN (*.7z, *.avi) do (
...
if "%~1" NEQ "" goto while
goto :eof

which executes the second routine as en internal subroutine (the : in the call is required) providing that routine with a fresh copy of the parameter-list (%*)

You could also consider moving the if "~1"... to the start of the routine (just after the :while), change it to if "%~1" EQU "" goto :eof and change the final statement to goto while.

The label :eof is defined as end-of-file by cmd and should not be declared.

Upvotes: 0

Related Questions