Age-Based File Deletion in WSH - Deleting files based on age
(Page 5 of 5 )
numDays = 7
strPath = "C:\Windows\Temp"
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FolderExists(strPath) Then
Set objFolder = objfso.GetFolder(strPath)
Call CheckFolder(objFolder, numDays, True)
Else
WScript.Echo "The specified folder", strPath, "does not exist"
End If
Sub CheckFolder(objFolder, numDays, bRecurse)
Set colFiles = objFolder.Files
If colFiles.Count > 0 Then
For Each objFile In colFiles
Call DeleteOldFile(objFile, numDays)
Next
Else
WScript.Echo "No files in folder", objFolder.Path
End If
If bRecurse Then
Set colSubfolders = objFolder.SubFolders
If colSubfolders.Count > 0 Then
For Each SubFolder In colSubfolders
CheckFolder SubFolder, numDays, True
Next
End If
End If
End Sub
Sub DeleteOldFile(objFile, numDays)
On Error Resume Next
Err.Clear
dateFile = objFile.DateLastModified
dateToday = Now()
If dateFile <= dateToday Then
daysOld = dateToday - dateFile
If daysOld > numDays Then
strFile = objFile.Path
objFile.Attributes = 0
objFile.Delete
If Err.number <> 0 Then
WScript.Echo Err.number, Err.Description, Err.Source, _
strFile
Call RemoveOnReboot(strFile)
Else
WScript.Echo strFile, "deleted"
End If
End If
Else
WScript.Echo "Incorrect date stamp in", strFile
End If
End Sub
Sub RemoveOnReboot(strFile)
Const HKLM = &H80000002
strComputer = "."
Set objReg = GetObject("winmgmts:" & strComputer & _
"\root\default:StdRegProv")
strKey = "SYSTEM\CurrentControlSet\Control\Session Manager"
strName = "PendingFileRenameOperations"
objReg.GetMultiStringValue HKLM, strKey, strName, arrValues
If IsNull(arrValues) Then
arrValues = Array("\??\" & strFile, "")
Else
ReDim Preserve arrValues(UBound(arrValues) + 2)
arrValues(UBound(arrValues) - 1) = "\??\" & strFile
arrValues(UBound(arrValues)) = ""
objReg.DeleteValue HKLM, strKey, strName
End If
objReg.SetMultiStringValue HKLM, strKey, strName, arrValues
End Sub
You should be able to find many different uses for this type of script and there is a lot of room for improvement as well. Consider adding some logging or better error-handling. What would happen if you used the DateCreated or DateLastAccessed method instead of DateLastModified?
I hope I’ve been able to shed a little light on the subject of age-based file deletion and maybe prevented a question or two. Until next time, keep coding!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |