# Batch file for mass deletion of files and directories



## timmyo (Mar 11, 2010)

Hey there!

I'm hoping someone can help me out with a unique situation type. I'm looking to create a batch file using standard Windows shell commands that will help automate file and subdirectory deletion.

The scenario is this: I have a directory that contains an undefined number of old jobs (1500, 1501, 1502, etc). Inside each of these jobs, there are an undefined number of files and potential subdirectories. These could be temporary files or anything else.

I need to have this batch look into my 'jobs' folder, see that there are a number of first level folders with the sequential names, see that there are other files and folders inside of _these _and delete whatever are in them.

I attempted a modified version of a loop using RMDIR based somewhat on a situation found in this thread:
http://forums.techguy.org/dos-pda-other/706218-bat-file-del-sub-folders.html

The trouble with the issue described there is that the names of the directories must be defined and consistent. I can name a few as I see and have them deleted just fine, but I can't use this to delete random files.

Any pointers? I've probably done a terrible job of explaining the hierarchy but if anyone needs any further info, I'd be glad to oblige. Thanks so much for your help in advance!


----------



## Squashman (Apr 4, 2003)

You need a base working folder. Any folder in that base folder should be deleted using this.


```
for /D %%I in ("C:\oldjobs\*") do rmdir /s/q "%%I"
```


----------



## timmyo (Mar 11, 2010)

Hey thanks for the quick response!

I gave this a try in a test environment, but unfortunately it goes one step beyond what I'd like it to do. When the base is set to "C:\oldjobs" it deletes everything in that directory.

In this case, I'll need to retain my numbered job folders and simply delete what's inside of them.

Thanks for your help so far!


----------



## Squashman (Apr 4, 2003)

How do you expect something to be able to pick and chose what directories to delete without know the directory names?


----------



## Squashman (Apr 4, 2003)

Can you give us an example of the directory structure?
Are the folders that you want to delete only named as numbers?
Got an idea if they are only named as numbers.


----------



## timmyo (Mar 11, 2010)

That's a great question.

It's safe to assume that inside that base jobs folder, items will remain untouched.

I need to figure out how to have that base ignored, and look into any subdirectory, then delete whatever it finds in a subdirectory--regardless of the file type (whether there be another directory, etc)

In a sense, it can be said that I need to scan this jobs folder, realize that there are levels WITHIN jobs, and delete anything found beyond that first level. For example, old job folder 1400 may have a bunch of temp files, then subdirectories with even more files.


----------



## timmyo (Mar 11, 2010)

And for an example we'll say it's laid out like this:

C:\jobs
C:\jobs\1500
C:\jobs\1501\applicationtemp\morefileshere.file
C:\jobs\1502\different\stilldifferent\temp

So on and so forth. It's safe to assume that these folders are all sequentially named (they SHOULD be) but I won't know what the names of the folders are until I actually go to delete them.


----------



## Squashman (Apr 4, 2003)

are there any other folders or files in the jobs folder that are named specifically with numbers only that should not be deleted.


----------



## timmyo (Mar 11, 2010)

For the purposes of my sanity, I'll assume that in the jobs folder, there are only folders, named with job numbers.


----------



## TheOutcaste (Aug 8, 2007)

So you want to delete the contents of the 15XX folders (names unknown), but not the 15XX folders themselves?
*EDIT: To be clear, this will clear all folders under the base C:\jobs, not just those that start with 15*
This should do it. Set the _Commit flag to True to actually delete files and folders. Otherwise it shows each folder and the command that will be run

```
@Echo Off
:: Clear Subfolders
:: Removes all files and subfolders of the first level folders
:: First level folders are not removed
:: Specify the top level folder that contains the first level folders here
Set _Base=C:\jobs
:: Set Commit to True to actually delete the files and folders
Set _Commit=True
If Not "%_Commit%"=="True" (Call Set _T=Echo.!cd! - ) Else Set _T=
SetLocal EnableDelayedExpansion
PushD "%_Base%"
For /F "Tokens=1 Delims=" %%A In ('Dir /AD /B') Do (
  PushD "%%A"
  %_T%Del /Q /F *.*
  For /F "Tokens=1 Delims=" %%I In ('Dir /AD /B') Do %_T%RD /Q /S "%%I"
  PopD
)
PopD
```


----------



## Squashman (Apr 4, 2003)

I think this is doable. Got a couple of different ideas.
I just don't understand why would keep the job folder and delete everything in it.


----------



## Squashman (Apr 4, 2003)

TheOutCaste's solution will work. I was just worried about deleting other folders and files in your base folder that were not job folders.


----------



## Squashman (Apr 4, 2003)

Was chatting with TheOutCaste and we came up with another solution just as a safe guard. 
This iteration will only work on folders inside your jobs folder that are named as numbers.

So if you have these two folders:
c:\jobs\1501
c:\jobs\A123

It will only work on the folder named 1501.


```
@Echo Off
:: Clear Subfolders
:: Removes all files and subfolders of the first level folders
:: First level folders are not removed
:: Specify the top level folder that contains the first level folders here
:: Oringal done by TheOutCaste http://forums.techguy.org/dos-pda-other/909318-batch-file-mass-deletion-files.html
:: Modified to work only on folder names that are numbers.
Set _Base=C:\Test Dir1
:: Set Commit to True to actually delete the files and folders
Set _Commit=True
If Not "%_Commit%"=="True" (Call Set _T=Echo.!cd! - ) Else Set _T=
SetLocal EnableDelayedExpansion
PushD "%_Base%"
For /F "Tokens=1 Delims=" %%A In ('Dir /AD /B') Do (
  Set /a _Temp=
  Set /a _Temp=1%%A 2>Nul
  If Defined %_Temp% (
     PushD "%%A"
     %_T%Del /Q /F *.*
     For /F "Tokens=1 Delims=" %%I In ('Dir /AD /B') Do %_T%RD /Q /S "%%I"
     PopD
   )
)
PopD
```


----------



## timmyo (Mar 11, 2010)

Well then, that's pretty awesome!

Thanks so much for your help thus far guys.

The reasoning for keeping the job numbered files is that they've been pre-setup using a database associated to real jobs. The clients that we're working on essentially have a project file that automatically writes temp files to the corresponding numbered folder in this "jobs" folder.

In order to clear out space, and save a bunch of time, we need to be able to flush out old work without killing the folder and needing to recreate it. I was just trying to figure out how I could automate the whole process.

I'm going to do some further testing on this stuff and give you a result as I work through.

Could you do some explaining as far as what each step is taking care of?

Seriously thanks so much for the help on this stuff. You've shed a LOT of light on this for me.


----------



## TheOutcaste (Aug 8, 2007)

This is numbered to match the lines in the code. If you aren't using an editor that shows line numbers, I'd recommend Notepad++. Great little tool.
Comments removed as they should be self-explanatory.

```
01 - Turn off echo
08 - Specify base folder
10 - This variable is used for testing. If not set to [B]True[/B] (case sensitive) if only echos commands, doesn't actually delete anything
11 - Checks the Commit flag and sets a variable to insert an Echo command if not set to [B]True[/B]
     The variable is set to "[B]Echo.!cd! - [/B]" which Echos the current folder then everything else on the line
     The ! is used instead of % as it's inside a loop. This tells the command processor to use Delayed Expansion
12 - Enables Delayed Expansion, needed to display the current directory inside the For loops when in test mode
13 - Change to the Base folder, saving the current folder so we can return
14 - The Dir command gets a list of folders inside the base folder.
     The For loop will process each folder one at a time
15 - Clears the _Temp variable
16 - Using [B]/A[/B] forces Set to treat the folder name as a number. If it contains any non-numeric characters it fails, leaving _Temp undefined.
     The error is redirected to Nul so it won't display
17 - If the _Temp variable is defined, the folder name was numeric, so the next four lines will be executed
18 - Switch to the numbered folder, saving the current one so we can return
19 - Deletes all files in the numbered . If _T is defined, it echos the Current Directory then the Del command instead of executing the Del command
20 - This loop gets a list of all subfolders in the numbered folder and uses RD to remove them
     If the _T variable is defined, it just echos the command
21 - Return to the previous folder (the base folder)
22 - Ends the If statement that checked the _Temp variable
23 - Ends the first For loop that gets each top level folder name
24 - Returns to the folder we started in when this batch file was executed.
```


----------



## timmyo (Mar 11, 2010)

thanks so much for your help on all this guys.

looks like I got it working in a way that will suit my situation best. NOW I just need to figure out how to to make the base folder a variable so that I can run it from a command line on any given "base" and have it ask me to make sure I want to.

any pointers?


----------



## Squashman (Apr 4, 2003)

You can run the batch file from the cmd prompt with input. Any input you put on the CMD line with be reference in the batch file as %1 %2 %3 Make sure you put spaces around the path if it has spaces.

yourbatch.bat "C:\Documents and Settings\Squashman"


----------



## Squashman (Apr 4, 2003)

If you really want to make it special, you can call a Vbscript that lets you select the folder.
http://blogs.technet.com/heyscripti...g-box-that-only-lets-them-select-folders.aspx


----------



## TheOutcaste (Aug 8, 2007)

This will let you drop the folder, or specify it on the command line. Checks to make sure it's a folder and not a file as well.

```
@Echo Off
:: Clear Subfolders
:: Removes all files and subfolders of the first level folders
:: First level folders are not removed
:: Specify the top level folder that contains the first level folders here
:: Original done by TheOutCaste http://forums.techguy.org/dos-pda-other/909318-batch-file-mass-deletion-files.html
:: Modified to work only on folder names that are numbers.
If "%~1"=="" Goto _Usage
Echo. Warning! This will delete all files in the subfolders in %1
Set /P _Resp=Are you sure?(y to continue, anything else exits): 
If /I NOT "%_Resp%"=="y" Goto :EOF
Set _Base=%~1
Set _Chk=%~a1
If "%_Chk:~0,1%"=="d" Goto _Process
Echo %1 is not a valid Folder name
Goto _Usage
:_Process
:: Set Commit to True to actually delete the files and folders
Set _Commit=True
If Not "%_Commit%"=="True" (Call Set _T=Echo.!cd! - ) Else Set _T=
SetLocal EnableDelayedExpansion
PushD "%_Base%"
For /F "Tokens=1 Delims=" %%A In ('Dir /AD /B') Do (
  Set /a _Temp=
  Set /a _Temp=1%%A 2>Nul
  If Defined %_Temp% (
     PushD "%%A"
     %_T%Del /Q /F *.*
     For /F "Tokens=1 Delims=" %%I In ('Dir /AD /B') Do %_T%RD /Q /S "%%I"
     PopD
   )
)
PopD
Goto :EOF
:_Usage
Echo.%~dp0 Folder
Echo.  Folder  :Name of the base folder to process
Echo.          :Specify on command line or drop it on this file
Echo.          :Must be quoted if it contains spaces.
```


----------



## Squashman (Apr 4, 2003)

Squashman said:


> If you really want to make it special, you can call a Vbscript that lets you select the folder.
> http://blogs.technet.com/heyscripti...g-box-that-only-lets-them-select-folders.aspx


Guess I should elaborate on that. You need your batch file and a separate vbscript.

Batch file

```
@Echo Off
:: Clear Subfolders
:: Removes all files and subfolders of the first level folders
:: First level folders are not removed
:: Specify the top level folder that contains the first level folders here
:: Oringal done by TheOutCaste http://forums.techguy.org/dos-pda-other/909318-batch-file-mass-deletion-files.html
:: Modified to work only on folder names that are numbers.

:: getting base folder with VBscript
cscript.exe //nologo //H:cscript>nul
for /f "tokens=*" %%i in ('GetFolder.vbs //nologo') do set _Base=%%i
cscript.exe //nologo //H:wscript>nul

:: Set Commit to True to actually delete the files and folders
Set _Commit=True
If Not "%_Commit%"=="True" (Call Set _T=Echo.!cd! - ) Else Set _T=
SetLocal EnableDelayedExpansion
PushD "%_Base%"
For /F "Tokens=1 Delims=" %%A In ('Dir /AD /B') Do (
  Set /a _Temp=
  Set /a _Temp=1%%A 2>Nul
  If Defined %_Temp% (
     PushD "%%A"
     %_T%Del /Q /F *.*
     For /F "Tokens=1 Delims=" %%I In ('Dir /AD /B') Do %_T%RD /Q /S "%%I"
     PopD
   )
)
PopD
```
GetFolder.vbs

```
Const MY_COMPUTER = &H11&
Const WINDOW_HANDLE = 0
Const OPTIONS = 0

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_COMPUTER)
Set objFolderItem = objFolder.Self
strPath = objFolderItem.Path

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder _
    (WINDOW_HANDLE, "Select a folder:", OPTIONS, strPath) 
      
If objFolder Is Nothing Then
    Wscript.Quit
End If

Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path

Wscript.Echo objPath
```
But I like Jerry's idea. He helped me with a drag n drop batch the other day and it works quite nicely.


----------



## alan.b (Sep 5, 2007)

timmyo said:


> The reasoning for keeping the job numbered files is that they've been pre-setup using a database associated to real jobs. The clients that we're working on essentially have a project file that automatically writes temp files to the corresponding numbered folder in this "jobs" folder.
> 
> In order to clear out space, and save a bunch of time, we need to be able to flush out old work without killing the folder and needing to recreate it. I was just trying to figure out how I could automate the whole process.


Why not replace this dumb "project file" which only knows where it wants to automatically write temp files,
with something more intelligent that is able to first of all detect absence and automatically recreate the intended destination folder ?

Alan


----------



## Squashman (Apr 4, 2003)

alan.b said:


> Why not replace this dumb "project file" which only knows where it wants to automatically write temp files,
> with something more intelligent that is able to first of all detect absence and automatically recreate the intended destination folder ?
> 
> Alan


If you are going to criticize without knowing all the information at least offer to help the person.


----------



## alan.b (Sep 5, 2007)

Squashman said:


> If you are going to criticize without knowing all the information at least offer to help the person.


"Without knowing all the information" I prefer to learn enough of the situation before I offer possibly irrelevant help.
If "project file" involves a batch script then a deleted folder can be easily detected and recreated,
and I know the precise DOS commands to do that - but that is probably not relevant.
Hence I asked a simple question.

I view as fatally flawed any set of software that cannot instantly recreate a desired destination folder for its output file.
Unfortunately some commercial Windows applications are flawed, and need re-installation so they can recreate folders.

As a real time embedded software designer I have some experience of being given a requirements specification and spotting flaws and gaining approval for improvements to the specification.

I have NOT criticized timmyo.
I am critical of the dumb "project file" which is not under his control, and has inadequate error detection/correction.

Regards
Alan


----------

