12

I am trying to write a Windows Batch file that will allow me to move all directories within a given source directory into a target directory that exists within that source directory.

Obviously my move command with need to only apply to directories and also exclude the target directory from being processed.

Is this possible with a Windows batch command?

7 Answers 7

14

Robocopy (present in recent versions of windows or downloadable from the WRK) can do this, just use the /xd switch to exclude the target directory from the copy;

robocopy c:\source\ c:\source\target\ *.* /E /XD c:\source\target\ /move
1
  • What about multiple exceptions or multiple directories to skip in moving ? Improve your answer by adding that too.
    – Vicky Dev
    Nov 13, 2017 at 8:45
7
FOR /d %%i IN (*) DO IF NOT "%%i"=="target" move "%%i" target
1

That won't work - you'll get an error telling you the target directory is inside the source directory or so, even if you explicitly exclude the target directory. What you can do is move the directories to a temporary location which is not under the source, and then move them into the target.

BTW, using the move command won't let you specify folders to exclude. For that you can use xcopy, but note that it will copy the folders, as opposed to move them. If that matters, you can delete whatever you want afterwards, just make sure you don't delete the target dir, which is in the source dir...

1

Using robocopy included with Windows 7, I found the /XD option did not prevent the source folder from also being moved.

Solution:

SET MoveDirSource=\\Server\Folder
SET MoveDirDestination=Z:\Folder
FOR /D %%i IN ("%MoveDirSource%\*") DO ROBOCOPY /MOVE /E "%%i" "%MoveDirDestination%\%%~nxi"

This loops through the top level folders and runs robocopy for each.

1

NB: Robocopy mentioned above using the /move flag will copy the files and then delete them from the source folder rather than moving the files. This may be critical if moving large numbers of files from one location to another on the same disk (because move is virtually instantaneous, while copying is a much slower operation)

1

On windows batch:

FOR /d %%i IN (MySourceDirectory\*) DO move "%%i" MyTargetDirectory\%%~ni

The above command moves all directories found in MySourceDirectory (/d) to MyTargetDirectory using the original directory name (~ni) Robocopy's move first does a copy, then delete, so it is slower.

0

This works for me:

move c:\fromDir\*.* c:\toDir\
1
  • 1
    at least on winserver2012r2, this does work only for moving files, but not subdirectories - and does not cover any option for 'exceptions' Dec 1, 2017 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.