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).