tags:

views:

109

answers:

5

Hi, I'm trying to create a batch script that will delete all sub directories which are older than 30 days. I'm really new to batch scripting so I'm just hoping that someone can help me out on this.

I was able to find a script that delete all sub directories in specified location.

@for /f "tokens=*" %%a in ('dir /s /b "C:/temp/test" 2^>NUL') do rd /s /q "%%a"

Can someone tweak this script so it deletes only directories which are 30 days old?

A: 

You might want to consider using Windows Script Host, in which you could run a VBScript to do just that. Think of it like a batch file with more flexibility and power.

See http://www.computing.net/answers/programming/wsh-delete-files-in-folder-by-date/16255.html

JYelton
A: 

Assuming you are restricted to batch files... check this - but if you can use VBScript, I think you can do a bit better.


Now that you have clarified your real problem, please understand that if you meant to use System.exec() you will have to contend with plenty of drawbacks.

Alternatively if you really want to use JNDI (you mention "native" but don't make clear what you mean) maybe this will be of help: http://mindprod.com/products1.html#FILETIMES

p.marino
Oh thank you so much. That will save me lots of time.
Marquinio
A: 

This is not going to be a simple tweak. As it stands, there is no easy way (that I know of) to do the date-diff operation in the cmd interpreter.

First you'll have to parse the current date:

C:\>date /T
Thu 08/05/2010

Once you have the day, month, year, you have to get the date for each item in the directory listing, which you can do by removing the /b param in the dir command and modifying the tokens line to give you tokens 1 and 4, i.e. tokens=1,4, and then doing the date math yourself, which will be a pain because you have to handle different lenght months, and December -> January transitions (new years), etc, and you're almost certain to get it wrong.

Also add the /ad param to get just directories.

I would recommend using PowerShell or some other scripting technology that gives you the tools you need to manipulate dates.

jeffamaphone
A: 

I think FORFILES is going to do it...

FORFILES -D 30 will iterate all files last modified over 30 days ago

So, something like...

FORFILES /S /D -30 /C "cmd /c IF @isdir == TRUE rd @path"

Should (untested) recursively remove all folders older than 30 days :)

Btw - Check out http://ss64.com/nt/ for more command line goodness

Matt Roberts
+1  A: 

Do you have powershell on your system?

dir | ? { $_.LastWriteTime -lt [DateTime]::Now.AddDays(-30) } | % { rm $_.FullName }

mwilson