Search code examples
windowsbatch-filexcopy

Amending text file strings and using the result to perform an xcopy


I have a windows boot pen that runs a batch file when it starts up, all it needs to do is copy a large list of files specified in a text file from the machine to the boot pen.

I made a test run on my PC before making the boot pen and thought this should work

@echo off
set DRIVE=c

for /F "tokens=*" %%a in (e:\test\files.txt) do call :amendDirectoryAndCopy %%a

pause

:amendDirectoryAndCopy
set DEST=%~1
set DEST=%DEST:~1%
echo set DEST=%DRIVE%%DEST%
echo xcopy %~1 %DEST%

all it should do is for each file, remove the first character of the string, add "c" to the beginning which gives the destination directory, then perform an xcopy. I find the output confusing as "@echo set "DEST=%DRIVE%%DEST%" outputs what I would expect, the correct directory on C: such as

c:\test\folder\file.txt

but the xcopy outputs

xcopy e:\test\folder\file.txt :\test\folder\file.txt

the drive letter is missing on the destination.


Solution

  • I believe SetLocal EnableDelayedExpansion is needed along with its counterpart ! replacement of % in variable expansion to get your code to work.

    I am away from my Windows machine right now, so I cannot test the syntax, but off the top of my head, something like this should work:

    SetLocal EnableDelayedExpansion
    @echo off
    set drive=c    
    set ready_to_move=0  
    set file_list=e:\test\files.txt
    
    if "!ready_to_move!" == "1" (
      set echo=
    ) else (
      set echo=echo
    )
    
    for /F "eol=; tokens=1 delims=" %%f in ('type "!file_list!"') do (
      set source=%%~f
      for /f "tokens=* delims= " %%s in ("!source!") do set source=%%s
      set destination=!drive!!source:~1!
      !echo! xcopy "!source!" "!destination!"
    )
    

    Does this work for you?