How do I delete the oldest file in a folder using VBScript

Hi,

How do I search a specified folder "C:\security" and delete the oldest (last modified) file in that folder?

I want to run this on a Windows 2000 computer so I need an answer using VBScript / WMI.

Thanks
gran3085Asked:
Who is Participating?
 
ADSaundersConnect With a Mentor Commented:
Hi gran3085,
Try this,
Copy & paste to a .vbs file. Query your spelling above secuirty_ I have spelt as Security .. You may need to change it.

Dim fso, Fol, f, LowDt, FH
Set fso = CreateObject("Scripting.FileSystemObject")
Set Fol = fso.GetFolder("C:\Security")
Lowdt = DateAdd("d",1,Date()) ' Start from a date later than it could possibly be (tomorrow)
For Each f In Fol.Files
    If f.DateLastModified < Lowdt _
    And Left (f.Name, Len("Security_")) = "Security_" Then ' Check Spelling!!!!
        Lowdt = f.DateLastModified
        Set FH = f ' Store Handle
    End If
Next
'wscript.echo "Earliest file is " & FH.Name & " (" & CStr (FH.DateLastModified) & ")"
FH.Delete
Set f = Nothing
Set FH = Nothing
Set Fol = nothing
Set fso = nothing

Regards .. Alan
0
 
gran3085Author Commented:
Sorry I missed a bit.

What I actually want to do is scan a specified folder and delete the oldest file begining with "secuirty_"

In other words I have a folder called "C:\Security" with 5 files in it named:

secuirty_1.log
secuirty_2.log
secuirty_3.log
secuirty_4.log
someotherfile.log

Lets say that the "someotherfile.log" is actually the oldest and security_4.log is the next oldest. In this case I'd want to delete the secuirty_4.log file as it is the oldest file that starts with "security_"

Thanks
Pete
0
 
gran3085Author Commented:
Alan,

Thanks, thats perfect. I had to add "On error resume next" as it errored when there was no file to delete. But thanks fine.
Nice work!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.