Flatten directory structure

Solution 1:

There's no reason to use special tools or even scripting. Just use the search function in Explorer.

  1. Open the folder you wish to flatten in Explorer.
  2. Create a new folder, select all files (but not folders), and drag them to that folder (This will avoid getting two copies of those files.)
  3. In the search box (the one on the right of the address bar), type in * and press Enter.
  4. After the list populates, right click and select all, then right click and Cut.
  5. Press the back button to get back to the original folder, then right-click and paste.
  6. If you have any duplicate names, you will be prompted on how to deal with this. Choose the most appropriate option for your use case. (I would assume it would be to copy both files.) To avoid being prompted again, be sure to apply this to all files with the checkbox at the bottom.
  7. Select all folders, make sure they are empty by looking at the popup about the number of files selected, and then delete them.

If you would rather have a script so you can just start it and forget it, that can also be done. The command to replace mv *\* . is pretty easy (for /r %f in (*.*) do @move "%~f" .) but I'm sure you'd like to handle duplicates, without leaving them behind as in @Nicole Hamilton's answer. Appending a number to the filename of duplicates is probably the easiest way to do it.

Copy and paste the following batch file into Notepad and save it as "flatten.cmd" (including the quotation marks):

@echo off
cd "%~1"
md tempryfolder
move *.* tempryfolder
for /r %%f in ("*.*") do call :START "%%~f"
for /r /d %%f in (*.*) do rd "%%~f" 
GOTO :EOF
:START
setlocal
If exist "%~n1%~x1" set /a num=2
:LOOP
If exist "%~n1%num%%~x1" (
    set /a num+=1
    goto loop
)
move "%~1" "%~n1%num%%~x1"

To use the script, simply drag the folder you wish to flatten on top of it.

Solution 2:

You can flatten in Windows Explorer by navigating to the folder you wish to flatten and searching for System.Kind:<>folder to exclude folders from the results.

You can then select all the files with CTRL+A and copy and paste them into a new folder. Note that Windows Explorer will ask you how to deal with duplicate filenames.

enter image description here