0

I am writing a Win 7 batch script for copying files from various source paths to a single location. The full path names of the files being copied are listed in a text file.

The following script works when the source paths do not include spaces. I can handle spaces if path names are included into the script as constants with a combination of quotations and %~1. How do I emulate this combination for paths being passed as parameters?

Transfer2.bat:

set SOURCELIST=c:\Temp\List1.txt
set DEST=c:\Temp\To

for /f %%A in (%SOURCELIST%) do (forfiles /p %%~dpA /s /m %%~nxA /c "cmd /c copy /y @path %DEST%\@file" 2>>log.txt)

for /f %b in (log.txt) do (echo.%~b)>>log.txt`

del log.txt

List1.txt:

C:\temp\From\Test_This Space.txt
C:\temp\From\Test.txt

Results:

Transfer is successful for C:\temp\From\Test.txt.

Log returns ERROR: Files of type "Test_This" not found. for C:\temp\From\Test_This Space.txt.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • I would not use `forfiles` in this case because its variables like `@file` contain the enclosing `""` and so building a path like `%DEST%\@file` actually expands to `c:\Temp\To\"Test.txt"`... – aschipfl Jan 10 '16 at 17:53
  • Thank you for elaborating I_Know_Null's suggestion. – user3864446 Jan 10 '16 at 18:10

1 Answers1

1

Is forfiles command required for your script? If not, I think this is good enough:

@echo off
set SOURCELIST=C:\Temp\List1.txt
set DEST=C:\Temp\To

for /f "delims=" %%A in (%SOURCELIST%) do (
    copy /y "%%~fA" "%DEST%\%%~nxA" >>Log.txt 2>&1
)
type Log.txt
del /q Log.txt
pause
exit /b
Poypoyan
  • 446
  • 6
  • 15
  • @DennisvanGils - In my experience, quotes should -not- be used on SET commands. Quotes should be used when the variable is used. – lit Jan 11 '16 at 18:01
  • The quotes should be used, but like this: `set "SOURCELIST=C:\Temp\List1.txt"`. This prevents wrong syntax errors when the value contains a space, but will not put a quote around the value in the variable itself. – Dennis van Gils Jan 11 '16 at 18:08
  • @Liturgist Read the answers on [set environment variables with spaces](http://stackoverflow.com/a/34402887/3074564) and [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](http://stackoverflow.com/a/26388460/3074564) Those two answers explain why `set "variable=value"` and `"%variable%"` or `"!variable!"` should be used if a space is definitely included or could exist in string value assigned to a variable. But with `"%SOURCELIST%"` in the __FOR__ loop above it is additionally necessary to specify `usebackq`. – Mofi Jan 12 '16 at 06:13
  • Ok, ok, enough already. I thought the recommendation was to quote the value such as `SET THEDIR="C:\Users\me"`. That usually does not work out well. – lit Jan 12 '16 at 15:53