Search code examples
filebatch-filexcopy

How to loop in a folder with batch file


I need to do something with a batch file....

I need to copy a folder to another folder but...

If the new folder exist, I need to verify if the file in new folder exist, then I need to rename the file with «.old» at the end of this file before to copy the new file. I have a great experience of programming in Java, php etc, but not really with batch file...

I m using a syntax of java/php to explain my problem....

set folderOrigin=d:\test1
set folderFinal=d:\test5 
if EXIST %folderFinal% (
  for (fileOrigin : folderOrigin){
      variableNamefileOrigin = fileOrigin
      for (fileFinal : folderFinal){
          variableNamefileFinal = fileFinal            
          if (variableNamefileOrigin == variableNamefileFinal){
              newvariable = variableNamefileFinal + ".old"
              ren variableNamefileFinal newvariable
              xcopy /s /q %folderOrigin%+%variableNamefileOrigin% 
              %folderFinal%+%variableNamefileFinal% 
          }
      }
  }
) else (
    xcopy /s /q %dossierOrigine% %dossierDestinataire%
)
pause

Thx everyone !


Solution

  • Assuming that the source directory ("folders" are artifacts in the GUI; the structures in the filesystem are "directories") is %sourceFolder% and the destination directory is %finalFolder%; and also assuming that you need to copy only files (not an entire subtree):

    1. To loop through the files in %sourceFolder% you use a for loop:

      for %%f in ("%sourceFolder%\*") do call :copyOneFile "%%~f"
      exit /b
      
    2. In the subroutine :copyOneFile you have the current file as %1. To check whether it exists in %finalFolder% you use if exist, and if so you rename it, but not before checking if the .old file exists already:

      :copyOneFile
      
      if exist "%finalFolder%\%~nx1" (
        if exist "%finalFolder\%~n1.old" del "%finalFolder\%~n1.old"
        ren "%finalFolder\%~nx1" "%~n1.old"
      )
      
    3. Now you can copy the file from the source folder to the destination folder:

      copy "%~1" "%finalFolder%
      

    To understand the constructions %~nx1 and so on, use for /?. Note than the second argument of ren must have only the filename, a path is not allowed.

    If you need to copy an entire subtree then:

    • After copying the files, redo with for /d to get directories.

    • Use the appropriate commands instead of del and copy.