Force remove an entire Windows folder tree at the command line

Supposedly

del /f/s/q [target]
will delete an entire folder in Windows.

But often it doesn’t – excessively long file names, excessively long paths, and other things, break it. Sometimes it can be quite difficult to fully clean out a folder.

There are many solutions (cygwin‘s rm is pretty powerful) but here’s a simple batch file that harnesses the power of Robocopy (which comes pre-installed with Windows) to do the job:

@rem thanks to https://stackoverflow.com/questions/97875/rm-rf-equivalent-for-windows
@echo TEP - Terminate with Extreme Prejudice (die, die, die) @echo off setlocal SET /P AREYOUSURE=Are you ABSOLUTELY SURE you want to irreversibly delete folder '%1' [y,N]?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO abort set emptyFolder=%TEMP%\tep_%RANDOM%%RANDOM%%RANDOM%
mkdir %emptyFolder%
@REM robocopy will mirror an EMPTY FOLDER into the target
robocopy /mir %emptyFolder% %1 rmdir %emptyFolder% rmdir %1 goto exit :abort echo Nothing done. :exit endlocal

The only thing I’ve found that this won’t delete is open files.

Leave a Reply

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