Putting code into registry command key

I'm trying to do what's done in this question, but I want to attach it to a context menu on Directory so I can right-click on "Flatten Folder" and have it do it for me. That is, bring all the individual files within that folder up to the current directory, then delete the empty directory.

How can I flatten out a folder in Windows 7, assuming all file names are different?

I'm not sure what I'm doing wrong? In the registry command key I've got:

 cmd /K "for /f %f in ('dir "%1\*" /s/b/a-d') do if not %~ff"=="%1" move "%f" "%1"
&& for /f %f in ('dir "%1\*" /s/b/ad') do if not "%~ff"=="%1" rd /s/q "%f" pause"

EDIT: I have the context menu option, but when I click it I get an error saying that the foldername application is not found.

UPDATED My registry change looks like this: Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\Flatten Folder]
@="Flatten Folder"

[HKEY_CLASSES_ROOT\Directory\shell\Flatten Folder\command]
@="cmd /K \"for /f %f in ('dir \"%1\\*\" /s/b/a-d') do if not %~ff\"==\"%1\" move \"%f\" \"%1\""

Still no dice, but no error either.


Your problem is that the line in command is not executed through cmd.exe – it is executed through Explorer, which does not understand cmd.exe's built-in for command. You will need to put your script in a separate file (e.g. flatten.cmd) and run that. (Note that you will need to change %f to %%f then.)


I realize this topic is a few months old but here is my take on the command as regards to a context menu:

The script by itself:

(FOR /f "usebackq delims==" %%F IN (`DIR "%1" /a-d/b/s`) DO IF NOT EXIST "%1\%%~nxF" MOVE "%%F" "%1") && (FOR /f "usebackq delims==" %%F IN (`DIR "%1" /ad/b/s ^| SORT /r`) DO RD "%%F")

As a .REG file:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Shell\FlattenFolder]
@="Flatten Folder"

[HKEY_CLASSES_ROOT\Directory\Shell\FlattenFolder\command]
@="CMD.EXE /c (FOR /f \"usebackq delims==\" %%F IN (`DIR \"%1\" /a-d/b/s`) DO IF NOT EXIST \"%1\\%%~nxF\" MOVE \"%%F\" \"%1\") && (FOR /f \"usebackq delims==\" %%F IN (`DIR \"%1\" /ad/b/s ^| SORT /r`) DO RD \"%%F\")"

This is tested and working on a Win 7 setup. First of all, the script will NOT move a file to the root directory if there is already a file with that name. Secondly, the script then, in reverse, removes all empty directories, skipping any that might not be empty due to a naming conflict. I believe the issue @MAW74656 was having is due to spaces in the pathnames. The "usebackq delims==" addresses this problem.

The plus side of this implementation is that it works. It does not touch same-named files. It will not remove a directory unless it is empty.