Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Script to Delete Files

Status
Not open for further replies.

maltman1

Technical User
Nov 27, 2007
15
US
Hello all,

I am using the below script to delete files based on creation date but I can not get it to work. For example, I want to delete a file that is 30 minutes old. I eventually want it for 24 hours but I am trying to test it by using a smaller interval. Here is the script:

Dim fso, startFolder, OlderThanDate

Set fso = CreateObject("Scripting.FileSystemObject")
startFolder = "C:\Test\"

DeleteOldFiles startFolder

Function DeleteOldFiles(folderName)
Dim folder, file, fileCollection, folderCollection, subFolder

Set folder = fso.GetFolder(folderName)
Set fileCollection = folder.Files
For Each file In fileCollection
If DateDiff("n", Now, file.DateCreated) < -30 Then
fso.DeleteFile(file.Path)
End If
Next

End Function

Right now the script deletes everything. I can't figure out what I have done. Any help would be greatly appreciated.
 
works fine for me. Add this line right before the IF THEN to check file conditions.

Code:
msgbox file.Name & vbNewLine & DateDiff("n", Now, file.DateCreated)

-Geates
 
It gives me a syntax error when I add that code.
 
Code:
Function DeleteOldFiles(folderName)
	Set objfolder = fso.GetFolder(folderName)
	Set fileCollection = objfolder.Files
	
	For Each file In fileCollection
		[red]msgbox file.Name & vbNewLine & DateDiff("n", Now, file.DateCreated)[/red]
		If DateDiff("n", Now, file.DateCreated) < -30 Then
			fso.DeleteFile(file.Path)
		End If
	Next
End Function

If you get any kind of error on the read line, it's likely that your fileCollection object is empty and thus any property of "file" DNE.

-Geates
 
you can do a file.Delete, rather than the FSO.DeleteFile? oh, perhaps that will mess up the fileCollection enumeration, i guess there is little or no difference in either approach
 
I got this to work with the following code. I added the echo and figured out that it was enumerating negatively. This seems to have fixed it.

Code:
Dim fso, startFolder

Set fso = CreateObject("Scripting.FileSystemObject")
startFolder = "C:\Test\"

DeleteOldFiles startFolder

Function DeleteOldFiles(folderName)
   Dim folder, file, fileCollection

   Set folder = fso.GetFolder(folderName)
   Set fileCollection = folder.Files
   For Each file In fileCollection
         'WScript.Echo file.Name, file.DateCreated, DateDiff("h", Now(), file.DateCreated)
      If DateDiff("h", Now, file.DateCreated) < -24 Then
        fso.DeleteFile(file.Path)
      End If
   Next 

End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top