ChemClaude
ChemClaude

Reputation: 51

Windows batch file - Variables in nested FOR loops

I've a list of users in a text file (users.txt) and I want, for each user, to copy every file in their directory (c:\Folder\username) and subdirectory in another directory without subdirectory (c:\Folder 2\username).

I'm now using a batch file containing something like this:

for /f %%u in (user.txt) do (
    for /r "C:\Folder\%%u" %%f in (*.*) do @xcopy "%%f" "C:\Folder 2\%%u" 
)

...but is not working.

After some tests I was able to find out what's wrong: the first %%u variable in the second FOR

for /r "C:\Folder\%%u" %%f in (*.*) do @xcopy "%%f" "C:\Folder 2\%%u"

is not correctly replaced by the username.
Instead the second %%u (inside the DO command) is correctly replaced by it's value.

Is there a way to force the first %%u variable to take the correct value?

Upvotes: 2

Views: 3855

Answers (2)

Reinier Torenbeek
Reinier Torenbeek

Reputation: 17373

You could achieve this by calling a subroutine instead of nesting the loops. Something like:

for /f %%u in (user.txt) do call :doxcopy %%u
goto :eof

:doxcopy
for /r "C:\Folder\%1" %%f in (*.*) do @xcopy "%%f" "C:\Folder 2\%1" 
goto :eof

Upvotes: 1

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f %%u in (user.txt) do (
        pushd "C:\Folder\%%u" && (
            for /r %%f in (*) do @xcopy /i /y "%%f" "c:\Folder 2\%%u\" 
            popd
        )
    )

One simple solution is to remove the first for replaceable parameter from the recurse clause of the second for

Upvotes: 3

Related Questions