Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Deleting oldest file

Status
Not open for further replies.

lardum

IS-IT--Management
Apr 26, 2000
462
SE
I want to delete the oldest file in a folder. I'm using this script:

path = "C:\TEMP\TEST"
killdate = date() - 20

arFiles = Array()
set fso = createobject("scripting.filesystemobject")

SelectFiles path, killdate, arFiles

for n = 0 to ubound(arFiles)
set f = arFiles(n)
f.delete true
next

sub SelectFiles(sPath,vKillDate,arFilesToKill)

set folder = fso.getfolder(sPath)
set files = folder.files

for each file in files
on error resume Next
dtcreated = file.datelastmodified
on error goto 0
if not isnull(dtcreated) Then
if dtcreated < vKillDate then
count = ubound(arFilesToKill) + 1
redim preserve arFilesToKill(count)
set arFilesToKill(count) = file
end if
end if
next

end sub



Question no 1: Is there an easier way?
Question no 2: How can i exclude 2 files. I've tried with:
if f = "file1.txt" then
wscript.quit
end if
if f = "file2.txt" then
wscript.quit
end if
but this doesn't work. Any ideas?
 
Q2) Something like this ?
for n = 0 to ubound(arFiles)
set f = arFiles(n)
If LCase(f.Name) <> "file1.txt" And LCase(f.Name) <> "file2.txt" Then
f.delete true
End If
next


Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Try this it works for me !


Dim objFSO
Dim ofolder
Dim objStream

Set objFSO = CreateObject("scripting.filesystemobject")
CheckFolder (objFSO.getfolder("C:\Your Folder")), objStream

Sub CheckFolder(objCurrentFolder, objLogFile)

Dim strTemp
Dim strSearch
Dim strOutput
Dim strDate
Dim objNewFolder
Dim objFile
Dim objStream

strSearch = ".txt" 'enter your file extension here

For Each objFile In objCurrentFolder.Files
strTemp = Right(objFile.Name, 4)
If UCase(strTemp) = UCase(strSearch) Then
'Got one
strOutput = CStr(objFile.Path)
strDate = CDate(objFile.datecreated)

If Datediff("d", strDate, Now) > 60 Then
objFile.Delete
End If

End If
Next

'Recurse through all of the folders
For Each objNewFolder In objCurrentFolder.subFolders
CheckFolder
Next

End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top