Search code examples
batch-fileif-statementfor-loopxcopy

Nest if exist statement within for statement in batch file


Good morning guys. I have a batch file that searches network PC user folders for XML files, then copies those files to a network location. However, it copies folders for all users, regardless of whether they have the files in question. What I would like to do is only make a folder for that user if the directory in which those files are contained exists.

Here is what the code looks like:

for /d %%g in ("\\computer.domain\c$\users\*") do (
xcopy /d /q /c /i /y "%%g\AppData\Roaming\Program\Folder\*.xml" "\\server.domain\shared_folder\%%g"
)

It works perfectly but for creating a user folder for every user. What I would like to do is only create a folder for users where Appdata\Roaming\Program\Folder contains XML files in the first place. I can't figure out how to get an if exists statement to work within that for statement though. Also, this creates a directory structure like computer.domain/c$/users/user. If there is a way to strip out the c$/users (so it's computer.domain/user/file.xml), that would be even more amazing.

Thanks in advance!!

(Update) Here is the full code the batch is using. It repeats for each computer:

net use k: \\computer.domain\c$\users
for /d %%g in ("k:\*") do (
forfiles /P "%%g\AppData\Roaming\Program\Folder" /m *.xml /D -7 /C "cmd /C del @path"
)
net use k: /delete
for /d %%g in ("computer.domain\c$\users\*") do (if exist "%%g\Appdata\Roaming\Program\Folder\*.xml" (
xcopy /d /q /c /y "%%g\AppData\Roaming\Program\Folder\*.xml" "\\server.domain\shared_folder\%%~nxg\")
)
forfiles /P /S "M:\MAS500\endicia-postback-archive" /m *.xml /D -60 /C "cmd /C del @path"

The entire functionality is to delete XML files a week or older, then copy the remaining files, then delete files from the server that are two months or older. That line is only at the end, but the other lines are repeated for each computer.
Perhaps there is a better way to go about it? When I run it this way, it seems like I don't get a folder for all users that meet the criteria. Thanks again!


Solution

  • Test this after altering the paths:

    Just commenting here that your use of the /d switch will limit the files being copied.

    @echo off
    for /d %%g in ("\\computer.domain\c$\users\*") do (
       if exist "%%g\AppData\Roaming\Program\Folder\*.xml" (
          xcopy /d /q /c /y "%%g\AppData\Roaming\Program\Folder\*.xml" "\\server.domain\shared_folder\computer.domain\%%~nxg\"
       )
    )