Tuesday, January 6, 2009

Script Code: Kix or VBscript - Deleting Old Files

Let's see about deleting files in a given folder which are older than 30 days from the current date.

The VBScript Way (one way out of many)...

   Const strFolder = "c:\myfolder"
   Const maxDays = 30

   Set objFSO = CreateObject("Scripting.FileSystemObject")
   If objFSO.FolderExists(strFolder) Then
       Set objFolder objFSO.GetFolder(strFolder)
       For each objFile in objFolder.Files
           If DateDiff("d", Now, objFile.DateModified) > maxDays Then
               objFSO.DeleteFile objFile
           End If
       Next
       Set objFolder = Nothing
   Else
       Wscript.Echo "error: folder not found"
   End If
   Set objFSO = Nothing

The KixTart Way (one way out of many)...

    ; requires DateTimeDiff() function (see link)
    $strFolder = "c:\myfolder"
    $fileName = Dir("$strFolder\*.*")
    $maxDays = 30
    While $fileName <> "" And @ERROR = 0
        $filePath$strFolder+'\'+$fileName
        $fileDate = GetFileTime($filePath, 0)
        ; $fileDate returns Last-Write date as "YYYY/MM/DD HH:MM:SS"
        If DateTimeDiff($fileDate) > $maxDays
            Del $filePath
        EndIf
        $fileName = Dir() ; retrieve next file in folder
    Loop

Just another comparison to help familiarize how each scripting language deals with some common tasks.

Post a Comment