Examples make it easier for everyone to understand the requirements for a task.
So let me start with an example.
Source directory C:\test1
contains following files:
- Test1.txt
- Test2.txt
- Test3.txt
Destination directory tree C:\test2
contains following directories and files:
For this example just file Test1.txt
should be copied to directory C:\test2
because Test2.txt
and Test3.txt
exist already in subfolders of C:\test2
.
So the directory tree C:\test2
should look as follows after batch file execution:
- Subfolder1
- Subfolder2
- Test1.txt
This can be achieved with:
@echo off
for %%I in ("C:\test1\*") do (
dir "C:\test2\%%~nxI" /A-D /B /S >nul 2>nul
if errorlevel 1 copy "%%I" "C:\test2\" >nul
)
It is also possible to do that with a single command line:
@for %%I in ("C:\test1\*") do @dir "C:\test2\%%~nxI" /A-D /B /S >nul 2>nul || copy "%%I" "C:\test2\" >nul
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
copy /?
echo /?
for /?
if /?