11 Mar
Posted by Network Jew as Hacks, How-Tos, Scripting, Software
Logging is great, but logfiles tend to build up and take up valuable disk space. There’s no built-in utility in Windows to automatically prune files out of a directory based on age. Luckily, it’s easy enough to script this using VBSCRIPT.
To use the script below, first determine how many days/months you want to use as your cutoff and enter it in the script in this snippet:
strPruneDate = DateAdd(“d”, -3, Date)
For the above example, I’m looking for files older than 3 days. You could change “d” to “m” and look for months if you like.
Next, you need to specify which directory you want, and enter the drive and path in the two strings below:
strDrive = “c:”
strPath = “temp”
In the above example, I’m using C:\Temp.
Save the text with .VBS extension, and double click it to run. Alternately, you could stick it in a batch file with commands like this and then use Windows Scheduler to run this every so often:
wscript prunefiles.vbs
Here’s the vbscript code:
Option Explicit
Dim strPruneDate, strDay, strMonth, strYear, strTargetDate, strDate
Dim strComputer, strDrive, strPath, strPathAlt, strName
Dim objWMIService
Dim colFiles, objFile
Dim colFolders, objFolder
Dim strFolderPath, strFilePath
Dim colSubFolders, objSubFolder
Dim strSubFolderPath, strSubFilePath
Dim colSubFiles, objSubFilestrPruneDate = DateAdd(“d”, -3, Date)
strDrive = “c:”
strPath = “temp”strPathAlt = Replace(strPath, “\\”, “\”)
strName = strDrive & “\” & strPathAltstrDay = Day(strPruneDate)
If Len(strDay) < 2 Then
strDay = “0″ & strDay
End If
strMonth = Month(strPruneDate)
If Len(strMonth) < 2 Then
strMonth = “0″ & strMonth
End If
strYear = Year(strPruneDate)
strTargetDate = strYear & strMonth & strDaystrComputer = “.”
Set objWMIService = GetObject(“winmgmts:\\” & strComputer)
Set colFiles = objWMIService.ExecQuery _
(“SELECT * FROM CIM_DataFile WHERE Drive = ‘” & strDrive & _
“‘ AND Path = ‘\\” & strPath & “\\’”)
Set colFolders = objWMIService.ExecQuery _
(“ASSOCIATORS OF {Win32_Directory.Name=’” & strName & “‘} ” _
& “WHERE AssocClass = Win32_Subdirectory ” _
& “ResultRole = PartComponent”)For Each objFile in colFiles
FilecreationdateCheck
NextSub FilecreationdateCheck
strDate = Left(objFile.creationdate, 30)
If strDate < strTargetDate Then
objfile.delete objFile.Name
‘ Replace w/ wscript.echo after testing
End If
End Sub
RSS feed for comments on this post · TrackBack URI
Leave a reply