[Solved] Copy first level folder and consolidate all the files within subfolders


I would use a for /D loop to iterate the first-level sub-directories, then a nested for /R loop to iterate through all files in the immediate sub-directories, then use copy to copy each file individually in order to achieve the flat destination directory hierarchy. To avoid file name collisions (meaning that files with the same name appear in different source sub-directory hierarchy levels), an if exist directive can be used. So here is the code:

rem // Loop through immediate sub-sirectories of main directory:
for /D %%I in ("D:\MainDir\*") do (
    rem // Temporarily change to the currently iterated sub-directory:
    pushd "%%~I" && (
        rem // Iterate through all files in the current directory recusrively:
        for /R %%J in ("*.*") do (
            rem /* Create destination directory if necessary, which is named like
            rem    the current directory, that is the first source sub-directory: */
            2> nul md "D:\CopyDir\%%~nxI"
            rem // Temporarily change to the destination directory:
            pushd "D:\CopyDir\%%~nxI" && (
                rem // Check for potential file name collisions:
                if not exist "%%~nxJ" (
                    rem // No collision, hence copy current file:
                    copy "%%~J" "%%~nxJ"
                ) else (
                    rem // Collision, so return an error message:
                    >&2 echo ERROR: "%%~nxI\%%~nxJ" already exists!
                )
                rem // Return from destination directory:
                popd
            )
        )
        rem // Return from currently iterated source sub-directory:
        popd
    )
)

1

solved Copy first level folder and consolidate all the files within subfolders