Windows – How to create batch file that delete all the folders named `bin` or `obj` recursively

batch filecommand linewindows 7

I have the need of deleting all bin & obj folders in a folder on my PC. So, I'm thinking of a batch file to do that but I'm not famaliar with batching file in Windows. Please help.

[Edit]

After discussion with user DMA57361, I got to the current solution (still having problem though, see our comments):

Create a .bat file, and paste the below command:

start for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"

OR

start for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s "%%d"

@DMA57361: When I run your script, I get the below error. Any idea?

alt text

Best Answer

This has been previously answered over on Stack Overflow, which is where I've taken the main thrust of this answer from.

Try the following command, you can run it from within cmd:

for /d /r . %d in (bin,obj) do @if exist "%d" rd /s/q "%d"

If you need other folders to be changed, then just add new items to the (bin,obj) set in the middle of the command.

This will delete everything matched without warning and without using the recycle bin - so, if you want a bit of extra safety, drop the /q from the call to rd at the end, and the system should ask you before each deletion.

for /d /r . %d in (bin,obj) do @if exist "%d" rd /s "%d"

If you intend to run the command from within a batch file, you will need to replace every instance of the variable %d with %%d, like so:

for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
OR
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s "%%d"

As per the conversion had in the question comments

If the command refuses to run in a batch file (unable to replicate here), try prefixing the command with start. Although this will start the process to run concurrently with the batch file, which may cause other issues, it seems more likely to work correctly.

Also, if you have files named obj or bin within the folder tree the command is working on, then you will receive an error message for each file encountered that has a matching name. These matched files are not deleted, and should not get in the way of the command deleting what it should. In other words, they can be ignored safely.

Related Question