Tuesday, April 26, 2011

Delete Files that older than N... days.

Today I have to schedule my server to Delete Files that older than 3 weeks. Because of my application, it stuck when I order that menu to display the ECG graph those are in a huge folder. So it query without SQL. That why I have to delete it!

First I thinking about Batch File. I think I cannot do it by only DOS command. I have to find out a solution.

After I search on google I have found one that so usefully. But I forgot to copy that to show you how come.

Just create DeleteFilebyOlderDate.vbs and copy these into it.

------------DeleteFilebyOlderDate.vbs---------------


Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Call DeleteFiles(fso.GetFolder("C:\Test"), 7, ".txt") '<----- Change this folder name to match with your case.
Sub DeleteFiles(srcFolder, daysCount, strExtension)
    Dim srcFile, filesCount
    filesCount = 0
    If srcFolder.Files.Count = 0 Then
        Wscript.Echo "No File to Delete"
        Exit Sub
    End If
    For Each srcFile in srcFolder.Files
        If DateDiff("d", Now, srcFile.DateCreated) < ((-1)*daysCount) Then
            If (strExtension="") Or (Right(UCase(srcFile.Name), Len(strExtension))=UCase(strExtension)) Then
                fso.DeleteFile srcFile, True
                filesCount = filesCount+1
            End If
        End If
    Next
    Wscript.Echo filesCount & " Files Deleted successfully"
End Sub

------------------------------------------------------

Hope these information help!
Thank you.