Search code examples
windowsbatch-filecmdcopyxcopy

Trying to set the path in batch file


I am trying to copy some pictures from one folder and move it to another folder using batch. I am having trouble in setting the path since the path contains spaces in it.If I remove the spaces from folder it works fine but with spaces it gives error that cannot find the path.. here is the code.

@echo off 

SET odrive=%odrive:~0,2%
setlocal enabledelayedexpansion

set backupcmd=echo
set backupcmd=xcopy /s /c /d /e /h /i /r /y

set "filesw=C:\Users\%USERNAME%\Numerical Analysis\*.png"

for /f "delims=" %%i in ('dir /s /b %filesw%') do (
  if "%%~xi"==".pdf" set "dest=D"
  if "%%~xi"==".docx" set "dest=P"
  if "%%~xi"==".zip" set "dest=Z"
  if "%%~xi"==".rar" set "dest=Z"
  if "%%~di"=="C:" if "!dest!"=="Z" set "dest=!dest!3"
  %backupcmd% "%%i" "%drive%\Personal\PICS\Wedding\Barat\MOVIE!dest!\"
)

@echo off 
cls

It would be really helpful if you guys help me fix this path problem.


Solution

  • The solution to your problem, specifically "setting the path since the path contains spaces in it" leading to "cannot find the path" is to "quote the filespec" Thus:

    for /f "delims=" %%i in ('dir /s /b "%filesw%"') do (
    

    In this way, the string between the double-quotes is used literally (although certain special characters with a meaning to batch like &^)! need to be escaped; that is, preceded by a caret ^). As you have it, the dir command will be executed with multiple arguments since spaces are separators and the variable filesw will be substituted literally into the dir command before execution - and like most commands, dir uses spaces (commas, tabs, semicolons) as separators.