Completely delete a folder in Windows using command line
Try:
rmdir /S your_directory
or:
rmdir /S /Q your_directory
to skip confirmation messages.
This happens to me a lot with my automated build scripts.
I guess the reason might be some application that has a file open in that directory with "share delete". I.e. the application allows a deletion of the file (which is why I figure the DeleteFile call doesn't fail), but the file will only disappear after said application has closed it's handle.
That means the file might still be there when the rmdir
command tries to delete the folder, hence the error message. Soon after that, said application will close it's handle, the file will disappear, and when you inspect the folder to see which file rmdir
was talking about it will be empty.
At least that's my theory.
The workaround proposed by Harry Johnston looks good. Only I would insert a pause in between the rmdir
commands. Of course Windows has no easily scriptable "pause" command (correction: ancient Windows versions don't, newer have - see comments). But if seconds granularity is enough one can use ping
to create a pause:
ping -n {desired_delay_in_seconds + 1} 127.0.0.1 >nul
So in total:
rd /s /q foo
:: retry once
if exist foo (
:: clear errorlevel
cmd /c
:: pause
ping -n 2 127.0.0.1 >nul
:: retry
rd /s /q foo
)
:: retry yet again
if exist foo (
cmd /c
ping -n 2 127.0.0.1 >nul
rd /s /q foo
)
:: give up
if exist foo {panic}
You may have some readonly files, you can use the del /F option to get rid of them using
del /S /F your_directory
rmdir your_directory
You could also have some hidden files and if you are really sure you want to delete them, then you can do this using
del /S /F /AH your_directory
rmdir your_directory
If this still fails, then either you do not have permission to delete some files, or some of the files are still in use.