1

I have a text file which contains things like:

"C:\Folder A\Test.txt"

I need to copy certain files and their respective containers to a new directory from a directory, but only those files I specify and their parent folder structures.

In my batch:

for /f "delims=" %%a in (C:\audit\test.txt) do (
  robocopy "%%~dpa" "Z:\" "%%~nxa" /E /COPY:DAT /PURGE /MIR /R:1000000 /W:30
)
pause

However, it fails the robocopy, probably to do with the trailing backslash. The Source gets mixed up and shows both the folder and the Z:. This means t he file name from %%~nxa is then part of the destination rather than the file to copy. Any ideas?

PnP
  • 3,133
  • 17
  • 62
  • 95

2 Answers2

2

The backslash is treated as an escape character in this case because it immediately precedes the closing ". If you append a . to the path, the result will be the same path but the backslash will no longer precede the closing " and therefore will not be treated as an escape character for the ending quote.

In the example you've posted both the source and target paths end with a \. Therefore you'll need to add a . to both:

for /f "delims=" %%a in (C:\audit\test.txt) do (
  robocopy "%%~dpa." "Z:\." "%%~nxa" /E /COPY:DAT /PURGE /MIR /R:1000000 /W:30
)
pause
Andriy M
  • 76,112
  • 17
  • 94
  • 154
0

/MIR will copy the directory structure recursively, even directories that do not conatin files names in test.txt. Please do not use double quotes for first parameter. /R:1000000 /W:30 /COPY:DAT are default values, so no need to set tehm explicitely.

Please try the folowing code:

for /f "tokens=* delims=" %%a in (C:\audit\test.txt) do (
  robocopy %%~dpa "Z:\" "%%~nxa" /E /PURGE /MIR 
)
pause

If you're using spaces and/or special symbols in file paths, you can try the code below taht uses copy comand:

@echo off
for /f "tokens=* delims=" %%a in (C:\audit\test.txt) do (
    if not exist "Z:\%%~pa" mkdir "Z:\%%~pa"
    copy /Y "%%~a" "Z:\%%~pnxa"
)
mihai_mandis
  • 1,578
  • 1
  • 10
  • 13
  • This may indeed solve the problem, but only if the paths do not contain special characters or spaces. – Andriy M Jan 27 '14 at 19:05
  • File paths are quoted (as it is mentioned in article comments), so no fear of spaces. Spacial characters - maybe yes. Maybe it doesn't worth to worry about them if user doesn't use files with special characters. – mihai_mandis Jan 27 '14 at 19:15
  • The tilde `~` causes removal of quotes, so if there are spaces anywhere in the path, `%%~dpa` without quotes will be treated as two (or more) parameters. – Andriy M Jan 27 '14 at 19:18
  • Sorry @Andriy M, you're right. Only hope is user doesn't use paths containing spaces. – mihai_mandis Jan 27 '14 at 19:21
  • Thanks for your help, however the main problem I face is keeping the permissions and timestamps, hence the robocopy. – PnP Jan 27 '14 at 19:28