How-to: Delete files older than N days from a folder. [DelOlder.vbs]

Option Explicit
'On error resume next
    Dim objFS
    Dim strDirectoryPath
    Dim objFolder
    Dim objFileCollection
    Dim objFile
    Dim intDaysOld

strDirectoryPath = WScript.Arguments.Item(0)
intDaysOld = WScript.Arguments.Item(1)

' Check the number of days is 1 or greater (otherwise it will just delete everything)
If (intDaysOld<=0) Then WScript.quit -1
wscript.echo "Delete files more than " & intDaysOld & " days old:"

If (IsNull(strDirectoryPath)) Then WScript.quit -1
wscript.echo "Delete from: " & strDirectoryPath
wscript.echo ""

    Set objFS = CreateObject("Scripting.FileSystemObject")
    set objFolder = objFS.GetFolder(strDirectoryPath)
    set objFileCollection = objFolder.Files

    For each objFile in objFileCollection
        If objFile.DateLastModified < (Date() - intDaysOld) Then
                Wscript.Echo objFile.Name & " " & objFile.DateLastModified
                'objFile.Delete(True)
        'To delete for real, remove the ' from the line above
        End If
    Next

Examples

cscript delolder.vbs "D:\Demo\log files" 90

“The long run is a misleading guide to current affairs. In the long run, we are all dead” ~ John Maynard Keynes


 
Copyright © 1999-2024 SS64.com
Some rights reserved