Firstly, apologies for my lack of knowledge in this area. I have been using a basic forfiles batch and have made some changes but I can't get the script to delete the folders also. Currently it works fine to delete all of the files, including files in subfolders but leaves the folders empty.

E.g. there are files and folders created in the Projects folder "C:\Files\Projects\" example:



How can I include to delete the folders in addition to the files, in the top directory and subfolders?

My current script which outputs the deleted files to a log file:

forfiles /p "C:\Files\Projects" /s /m *.* /D -7 /C "cmd /c del /q /s @path" >> C:\Script\Deleted.log

Thanks so much!


The del command does not delete folders.

To delete folders you need to use the rmdir (or rd) command.

Do you want to delete all empty folders or only folders that you've just deleted files from? In the first case you can use:

A simpler way, or rather trick, than rd with a loop etc. would be to use the robocopy command. What you will do is basically move the whole parent folder to itself, but adding the /S switch that will leave out empty folders, effectively deleting them:

Robocopy C:\Files\Projects C:\Files\Projects /S /Move

Together with your file-deleting command that would be:

forfiles /p "C:\Files\Projects" /s /m *.* /D -7 /C "cmd /c del /q /s @path" >> C:\Script\Deleted.log && Robocopy C:\Files\Projects C:\Files\Projects /S /Move >> C:\Script\Deleted.log
  • Thanks so much, I didn't know about the rd or rmdir commands. I simply changed 'del' to rmdir or rd and it works perfectly! – Neviden Jun 12 '19 at 0:32
  • @PimpJuiceIT, you were referring to why/how robocopy would work here? Added. – Yisroel Tech Jun 12 '19 at 1:37
  • /S copies folders but not empty ones, and /Move deletes all matching from the source (including the empty ones). – Yisroel Tech Jun 12 '19 at 2:14
  • robocopy ... ... /E /MOVE seems to do the same, to remove empty folders (quite unexpectedly, in my opinion)... – aschipfl Jun 12 '19 at 8:47

As already said, the del command (also erase) only deletes files; to remove directories use the rd command (also rmdir).

forfiles features a variable named @isdir to indicate whether the currently iterated item is a directory (value TRUE) or a file (value FALSE), so let us make use of this:

forfiles /S /P "C:\Files\Projects" /M * /D -7 /C "cmd /C if @isdir == TRUE (rd /S /Q @path) else (del /F /A @path)" >> "C:\Script\Deleted.log"

You may want to force deletion of read-only files (del /F) and to also delete hidden files (del /A).

Note that I changed the file mask from *.* to *, because forfiles would not match files with no extension with the former, since it treats wildcards differently than most cmd-internal commands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.