I am making a batch script and part of the script is trying to remove a directory and all of its sub-directories. I am getting an intermittent error about a sub-directory not be
Similar to Harry Johnston's answer, I loop until it works.
set dirPath=C:\temp\mytest
:removedir
if exist "%dirPath%" (
rd /s /q "%dirPath%"
goto removedir
)
As @gfullam stated in a comment to @BoffinbraiN's answer, the <dir>
you are deleting itself might not be the one which contains files: there might be subdirectories in <dir>
that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm
from UNIX. rm.exe
comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.
Batch script example:
set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"
The reason rd /s
refuses to delete certain files is most likely due to READONLY file attributes on files in the directory.
The proper way to fix this, is to make sure you reset the attributes on all files first:
attrib -r %directory% /s /d
rd /s %directory%
There could be others such as hidden or system files, so if you want to play it safe:
attrib -h -r -s %directory% /s /d
rd /s %directory%
Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.
robocopy - cmd copy utility
/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans
Create en empty dir like this:
mkdir empty
overwrite broken folder with empty like this:
robocopy /copyall /mir /b empty broken
and then delete that folder
rd broken /s
rd empty /s
If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode
I can think of the following possible causes:
For 1.) you can try runas /user:Administrator
in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.
For 2.) download Process Explorer, click Find/Find handle or DLL...
or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.
enter the Command Prompt as Admin and run
rmdir /s <FOLDER>