Move all subfolders from parent folder to a new unique created folder in the target location

Jakov93

New Member
Joined
Nov 5, 2023
Hi I made this batch code, to move all subfolders from "C:\1" to a new created folder inside folder "C:\2"
Code:
@echo off
  
set "sourceDir=C:\1"
set "destinationDir=C:\2"
set "newFolderName=NewSubfolder"
  
mkdir "%destinationDir%\%newFolderName%" 2nul
   
for /D %%I in ("%sourceDir%\*") do (
         move "%%I" "%destinationDir%\%newFolderName%\" )
   
pause

The code works fine, but I will run the command at regular intervals depending on the subfolders in "C:\1", so I need to check if the newly created folder name exists in the target location "C:\2", append sequential number to folder name.
Thanks
 
You can modify your batch code to check if the newly created folder name already exists in the target location and append a sequential number to the folder name if it does. Here's an updated version of your code:

```batch
@echo off

set "sourceDir=C:\1"
set "destinationDir=C:\2"
set "newFolderName=NewSubfolder"
set "folderExists="

:checkFolderExists
rem Check if the new folder name exists in the destination directory
if exist "%destinationDir%\%newFolderName%" (
set /a "counter+=1"
set "newFolderName=NewSubfolder%counter%"
goto checkFolderExists
)

mkdir "%destinationDir%\%newFolderName%" 2>nul

for /D %%I in ("%sourceDir%\*") do (
move "%%I" "%destinationDir%\%newFolderName%\"
)

pause
```

In this modified code, I've added a `:checkFolderExists` label and a loop that checks if the new folder name already exists in the destination directory. If it does, it appends a sequential number to the folder name and goes back to check again. Once a unique folder name is found, it creates the new folder and moves the subfolders into it.

Note that I've also added a `:checkFolderExists` label and a `counter` variable to keep track of the sequential number. The initial value of the counter is 0, and it gets incremented each time a folder with the same name is found in the destination directory.

You can customize the initial value of the `counter` variable by adding `set "counter=<initial_value>"` before the `:checkFolderExists` label if you want the appended numbers to start from a specific value.
 
Back
Top Bottom