0

I'm copying a lot of folders/subdirectories from one network drive to another, however, the names of these files aren't known and I only want to copy the contents of the folders that have a name match.

Ex: srcdir has folders f1, f3, f4, f9 and destdir has folders f3, f5, and f9: since the names of folders f3 and f9 match, the contents (files and subdirectories) of f3 & f9 found in srcdir will be copied into their respective folders in destdir.

I've tried using xcopy but it only copies the files, and I've also tried

robocopy C:\test1 C:\test2 /u /s

but that skips over everything.

How would I go about copying the contents of a folder from the source network drive into its matching folder in the destination drive? Here's the code I have so far:

@ECHO OFF
setlocal EnableDelayedExpansion
for /d %%i in ("C:\test1\*") do (
  for /d %%j in ("C:\test2\*") do (
    set srcdir="%%~nxi"
    set destdir="%%~nxj"
    if !srcdir! == !destdir! ( robocopy C:\test1 C:\test2 ) else (echo Notsame!)
    echo %srcdir%
    ping 130.11.160.2
  )
)
0

1 Answer 1

0

ROBOCOPY.exe

Robust File and Folder Copy.
By default Robocopy will only copy a file if the source and destination have different time stamps or different file sizes.

robocopy C:\test1 C:\test2 /u /s would raise ERROR : Invalid Parameter #3 : "/u".

You could use next code snippet

@ECHO OFF
SETLOCAL EnableExtensions
set "source=C:\test1"
set "target=C:\test2"
for /d %%i in ("%source%\*") do (
  for /d %%j in ("%target%\*") do (
    if "%%~nxi"=="%%~nxj" ( 
        robocopy "%source%\%%~nxi" "%target%\%%~nxi" * /s /e  
    ) else (
        echo "%%~nxi" Notsame! "%%~nxj"
    )
    rem please do not apply load global network    ping 130.11.160.2
    timeout /T 10
  )
)

However, you need not iterate target folder at all (read IF - Conditionally perform a command) and apply if exist:

@ECHO OFF
SETLOCAL EnableExtensions
set "source=C:\test1"
set "target=C:\test2"
for /d %%i in ("%source%\*") do (
    if exist "%target%\%%~nxi\*" ( 
        robocopy "%source%\%%~nxi" "%target%\%%~nxi" * /s /e  
    ) else (
        echo "%%~nxi" Notsame!
    )
    rem please do not apply load global network    ping 130.11.160.2
    timeout /T 10
)

Note the difference (test the existence of files and folders):

    rem test a folder existence
if exist "%target%\%%~nxi\*" (echo folder exists)         else (echo no such folder)

    rem test a folder OR file existence
if exist "%target%\%%~nxi"   (echo file OR folder exists) else (echo no such file/folder)

    rem test a file (NOT folder) existence would be a bit more complex
    rem (off current question topic) do it yourself in case of such demand 

Not the answer you're looking for? Browse other questions tagged .