How to recursively delete files but keep the directory structure through the Windows command prompt?

The other day, I had to clear a structure of hundreds of folders containing over 60Gb worth of logs that we moved to an archive file server. After copying the logs to the archive location, I had to delete all the files while keeping the folder structure. Being accustomed to high level languages for too long, I first wondered how to do this in a batch file. It turns out that the forfiles command would do the task rather simply and elegantly:

forfiles /p D:\Archive\ /s /c “cmd /c IF @isDir EQU FALSE (del /Q /F @file)”

forfiles parameters:
/p -> Path in which the forfiles command will search for files.
/s -> Orders the forfiles command to execute recursively in all subdirectories.
/c -> Command to execute for each file found by forfiles. The command must be in quotes and start with cmd /c.

As forfiles returns all files and folders found within the given path, I simply had to check that the file found is not a directory before deleting it silently using the /Q parameter (the /F parameter forces the deletion of read only files).

For the 60Gb worth of data I had, the command ran for a good 15 minutes and the job was done (no heavy CPU usage or anything else noticeable so it is safe to use even on production environment).

One Reply to “How to recursively delete files but keep the directory structure through the Windows command prompt?”

  1. Hello Francois,
    Thanks for the post.
    Also, you can use powershell to do the job :
    Get-ChildItem -Path d:\test -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force
    Emmanuel

Leave a Reply

Your email address will not be published. Required fields are marked *


*