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:
C:\Files\Projects\1\random.txt
C:\Files\Projects\2\test\hello.xlsx
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.logThanks so much!
2 Answers
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 /MoveTogether 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 4 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.