Search code examples
batch-filefor-loopxcopy

forfiles has space in folder path


I want to try the bat file to copy my log to other space.

My code:

REM get date
FOR /F "tokens=1-4 delims=/ " %%a IN ("%date%") DO (SET _MyDate=%%d/%%b/%%c)
echo _MyDate: %_MyDate%    
set _path= "D:\Logs\AddressBook Service"
set _path2= "E:\Logs_test\AddressBook Service"
forfiles /p %_path% /d -%_day% /m *.log /c "cmd /c xcopy @path %_path2%"

My question is How to solve the forfiles @path has spaces in folder path?

Like this: E:\Logs_test\AddressBook Service


Solution

  • set "_day=2"                             only my guess
    set "_path=D:\Logs\AddressBook Service"
    set "_path2=E:\Logs_test\AddressBook Service"
    forfiles /p "%_path%" /d -%_day% /m *.log /c "cmd /c echo xcopy @path \"%_path2%\\\" /D /E /-Y"
    

    Above code snippet with proper escaped " double quotes (surprisingly escaped using a backslash \" instead of common caret) should result in something like

    xcopy "D:\Logs\AddressBook Service\some name.log" "E:\Logs_test\AddressBook Service\" /D /E /-Y
    

    Note that operational xcopy is merely displayed for debugging purposes. Remove echo keyword no sooner than debugged.
    Adding a trailing backslash to xcopy target folder (%_path2%\\) seems to be facultative (optional) supplement.
    Finally, note double quotes in set "variablename=variable value" syntax.