Delete files older that 2 days with some exceptions

scriptingwindows-server-2003

I need to delete files older than two days inside a folder, except files last modified the 1st of each month. Forfiles does not support exceptions. Operating System is Windows Server 2003. Any idea?

Thank you all for help!

Best Answer

Quick and dirty VBScript here, it assumes UK date format for enumerating if the file is from the 1st of the month. If you use a different date format then change the trim command to grab the appropriate number positions. For example, a US date would be Mid(objFile.DateLastModified, 4, 2) = 01 rather than Left(objFile.DateLastModified, 2) = 01

Anyway, sorry for the dirty code... but it should get you started.

strFolder = "C:\DeleteTest"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFolder)
Set colFiles = objFolder.Files
strDaysOld = 2
'Get files from target folder
For Each File in colFiles
set objFile = objFSO.GetFile(strFolder & "\" & File.Name)
'Enumerate last modified date/time and delete if older than 2 days but where the date doesn't start with '01'
If objFile.DateLastModified < (Date() - strDaysOld) AND NOT Left(objFile.DateLastModified, 2) = 01 Then
objFSO.DeleteFile objFile, true
End If
Next