Cher
Cher

Reputation: 2947

how to move folders with a loop over folders (in batch)?

Situation:

I try to move files inside a loop in shell but my code is not working.

for /D %%F in (*) do (
   if "%%F" NEQ "%directoryToPutFilesIn%" (
     move /y "%%F" "%directoryToPutFilesIn%"
  )
)

After hours of testing it, I realized it's because %%F is pointing to the folder, hence the file cannot be moved.

Bad solution:

The way I made it work and confirmed my suspicions is by saving the value of %%F in another variable and using that variable on next turn to move the file. Note, what is following needs an initialisation of %precedentFile% for the first turn.

for /D %%F in (*) do (
move /y "%precedentFile%" "%directoryToPutFilesIn%"
   if "%%F" NEQ "%directoryToPutFilesIn%" (
     move /y "%%F" "%directoryToPutFilesIn%"
     set precedentFile=%%F
  )

Problem:

This solution is not practical and feels wrongs. Is there a way to adapt my current code to do it, or simply another way?

Upvotes: 4

Views: 3170

Answers (1)

prudviraj
prudviraj

Reputation: 3744

Try below code to move files from one folder to another in batch script:

for /f %%a in ('dir /a:-D /b') do move /Y "%%~fa" "%directoryToPutFilesIn%"

Explanation :

dir /a:-D /b : This command will list all files in the directory 
move /Y "%%~fa" "%directoryToPutFilesIn%" : This will move all files in the directory where this command is executed to the destination you have mentioned.
%%~fa : This command will get full qualified path of the file with it's name.

Try Below code Move directories : Below command will move directories in the Path where this command is executed to the destination provided. In this that will be H:\ Drive, Change it accordingly

for /D %%b in (*) do move /Y "%%~fb" "H:\"

Upvotes: 2

Related Questions