vineri, 19 august 2016

ASP Classic Recursively Delete Files (older than) and folders

In ASP Classic (VBScript), this piece of script will recursively walk through all subfolders and remove all files older than 6 hours (change it to days, weeks, months), and all empty subdirectories.



DeleteFiles("C:\cleanThisSub")

dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")

' recursively deletes files older than 6 hours and the empty directories
Sub DeleteFiles(ByVal sFolder)
    Set folderObj = fso.GetFolder(sFolder)
    dim aFiles, aSubFolders, aSubFolders2, file, folder, folderObj2
    Set aFiles = folderObj.Files
    Set aSubFolders = folderObj.SubFolders

    For Each file in aFiles
        if ( DateDiff("s", file.DateLastModified, Now()) > 6 * 3600 ) then
            'delete files older than 6 hours
            response.write "del " & file.Path & "<br>"
            fso.deleteFile(file.Path)
        End If
    Next

    For Each folder in aSubFolders
        Set folderObj2 = fso.GetFolder(folder.Path)
        DeleteFiles(folder.Path)
        Set aFiles = folderObj2.Files
        if aFiles.Count<1 then
            set asubfolders2 = folderObj2.SubFolders
            if aSubFolders2.Count<1 then
                ' subfolder is empty, can be removed
                response.write "rmdir " & folder.Path & "<br>"
                fso.deleteFolder(folder.Path)
            end if
        end if
    Next
  
End Sub

Niciun comentariu:

Trimiteți un comentariu