Link to home
Start Free TrialLog in
Avatar of SupermanTB
SupermanTB

asked on

Script to delete the oldest file in a folder

I've never really written Windows scripts before, although I do have a programming background.  What I'd like to do is write a script that will delete the oldest file (according to the date modified) in a particular folder once a day.  There will not be any more than 5 files in this particular folder at any given time.  

This script will be run in Windows Server 2008 R2.

Can someone offer a little assistance here?  Thanks very much.
Avatar of wshark83
wshark83
Flag of United Kingdom of Great Britain and Northern Ireland image

You can use the FOR Files function - See --> http://ss64.com/nt/forfiles.html

also some helpful examples on this website --> stackoverflow.com/questions/51054/batch-file-to-delete-files-older-than-n-days
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SupermanTB
SupermanTB

ASKER

Thanks very much.  I'm going to test this out.
Worked great!  Thanks very much!
Here's a VBS script approach in case you are interested.  Since you are new to scripting I tried to "over comment" a bit.  Save as a VBS file, adjust the file name at the top, and then run from a command line or BAT like:

cscript ee28272393.vbs

Right now it doesn't display any information about the file deleted, but that could be easily added if desired.

' Define locations of files to work with
strBaseDir = "c:\temp"

' Create file system object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Access base files folder
Set objFolder = objFSO.GetFolder(strBaseDir)

' Initialize date for loop below to find oldest file
datOldest = #1/1/2100#

' Look at each file in base folder
For Each objFile In objFolder.Files

   ' See if this is older than any we have found so far
   If objFile.DateLastModified < datOldest Then

      ' If older, save its date and name as the oldest up to now
      datOldest = objFile.DateLastModified
      strOldest = objFile.Path

   End If

Next

' Delete the oldest file
If strOldest <> "" Then
   objFSO.DeleteFile strOldest
End If

Open in new window

~bp
billprew, thanks so much for that.  I really appreciate the commenting.  It really makes the code clear.

I had already awarded points before you posted your comment.  I'm sorry I don't have any points to award you.
Not a problem on points, if it turns out to be useful for you that's all that matters.  I did borrow the code from a similar question, which was looking for the newest file, so didn't take too much effort.

Good luck,
~bp
Great!  Thanks very much! How can I do this for Oldest Folder too? Please!
Open a new question and ask that.


»bp