Batch script to delete specific folders

4

1

I want to be able to run a script at a parent folder that contains other folders, the script will delete all the folders of a certain name.

So for example to remove all the bin folders and only them: \parent\a\bin, \parent\a\subfolder\bin, \parent\b\bin.

I found a similar script here, but it doesn't seem to work:

for /d /r %%i in (bin) do @rmdir /s %%i

We probably need to empty the bin folder first and then remove it, how can it be done?

shinzou

Posted 2016-04-02T17:56:21.157

Reputation: 354

Answers

4

The script will delete all the folders of a certain name

You don't need to empty the directory as the rd option /s will do that for you.

Use the following batch file:

@echo off
setlocal enabledelayedexpansion
rem find directories called bin
for /f "usebackq tokens=*" %%i in (`dir /b /s /a:d bin`) do (
  rem delete the directories and any files or subdirectories
  rd /s /q "%%i"
  )
endlocal

Further Reading

DavidPostill

Posted 2016-04-02T17:56:21.157

Reputation: 118 938

Very cool, just to make sure I got it, does it go through a list of folders, matching each item with the last keyword (bin)? – shinzou – 2016-04-02T22:32:19.653

The dir finds all folders with the name bin and the for loops through them one by one for deletion. – DavidPostill – 2016-04-02T22:38:22.700