title: Batch script to copy/delete folders matching a certain name and preserving their directory tree
body: <p>I am wondering whether it is possible to write a batch script for <code>CMD.EXE</code> (Target system: MS Windows 2k3) for doing the following:</p>
  
  <p>Let us have folder <code>rootfolder</code> containing a lot of files and directories. Some of the subdirectories (at different levels) might be called <code>dirname</code>. I would like to create a folder <code>rootfolder2</code>, copying the directory tree structure of <code>rootfolder</code> but containing only  the folders <code>dirname</code> with their content. I would also like to delete the same folders after having them copied in <code>rootfolder2</code></p>
  
  <p>Example:</p>
  
  <pre><code>rootfolder
   `- dir1
   `- dir2
       `- filew
       `- dirname
           `- filey
   `- dirname
       `- file1
       `- dirx
           `- file2
   `- filez
  </code></pre>
  
  <p>And the output I'm looking for would be:</p>
  
  <pre><code>rootfolder
   `- dir1
   `- dir2
       `- filew
   `- filez
  
  rootfolder2
   `- dir2
       `- dirname
           `- filey
   `- dirname
       `- file1
       `- dirx
           `- file2
  </code></pre>
  
  <p>Can I do this without having to write a console application in C/C++/Java/etc.</p>
  
  <p>Thanks in advance,
  Joe</p>
  
  <hr>
  
  <p>Here's the answer to my question using simply xcopy and batch scripting:</p>
  
  <pre><code>@echo off
  setlocal ENABLEDELAYEDEXPANSION
  set StartDir=Folder1
  set BackupDir=Folder1 BK
  mkdir "%BackupDir%"
  call :ProcessDir "%StartDir%"
  exit /b 0
  :ProcessDir
      echo Processing directory "%~1"
      for /f "delims=" %%d in ('dir /ad /b "%~1"2^&gt;nul') do (
          if "%%d"=="foldername" ( 
              xcopy /s /e /i "%~1\%%d" "%BackupDir%\%~1\%%d" 
              rmdir /S /Q "%~1\%%d"   
          ) else ( 
              call :ProcessDir "%~1\%%~d"
          )
      )
      exit /b 0
  </code></pre>
  
  <p>credits go to: <a href="https://stackoverflow.com/questions/717171/recursive-renaming-file-names-folder-names-with-a-batch-file">recursive renaming file names + folder names with a batch file</a></p>