Need a script to loop through folders to look for a folder called "common" and delete all files older than 45 days with the exception of certain extensions and log the activity in a log file.

I am looking for a script that will look in a folder that is like a "users" folder.  It needs to find all the directories named "common" under these user folders and delete all the files in this directory and all the subdirectories older than 45 days.  We need it to create a log file for each day this ran with all the files deleted listed.
kerryhillAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

boowhupCommented:
This script searches a folder (strBaseFolder) and all subfolders for "common" in the name (you can define this in strSearchFile). It then tries to delete very file in that folder (but not subfolders) and if successfully deleted writes to a logfile.
strSearchFile = "common"
strBaseFolder = "d:\"
strdate = year(now) & month(now) & day(now)
strLogFile = ".\log-" & strdate & ".csv"
intOldDate = 45
'========================
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objBaseFolder = objFSO.GetFolder(strBaseFolder)
WriteToTxt "Time,Filename(Short),Filename(Full)"
ProcessFolder(objBaseFolder)
'=========================
 
Sub ProcessFolder(objFolder)
	On Error Resume Next
	For Each objSubFolder in objFolder.SubFolders
		For Each strExtension in arrDirectoryExtensions 
			if Instr(objSubFolder.Name,strSearchFile) then
				DeleteFiles(objSubFolder)
			end if
		Next
		ProcessFolder(objSubFolder)
	Next
	
	On Error Goto 0
End Sub
 
Function DeleteFiles(objFolder)
	For	Each objFile in objFolder.Files
		On Error Resume Next
		objFile.Delete
		if Err.Number = 0 then
			WriteToTxt GetDetails(objFile)
		end if
		On error Goto 0
	Next
End Function

Open in new window

0
kerryhillAuthor Commented:
Thanks, will this continue to look for subfolders named Common after it finds the first one?  There will be multiple "common" folders.
0
boowhupCommented:
yes, it will go through every sub folder from the "base" (root) folder , and work against each "common" found , then keep going. One thing I should mention, it looks for the word "common" in the name, so it would work against "xxcommonxx" as well as "common". I can change if necessary.
0
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

kerryhillAuthor Commented:
Great, is there a way to make is delete files over 45 days in the common folder recursively?
0
Robin CMSenior Security and Infrastructure EngineerCommented:
you'd need to define what you mean by "over 45 days". 45 days since when? Creation date? Last Accessed date? Last Modified date?

Just need to tweak the delete function as follows.

Swap objFile.DateLastModified for objFile.DateCreated or objFile.DateLastAccessed as appropriate.

The script above uses a sub called WriteToTxt to write the log but the code for that isn't supplied. You can just knock something basic up using objFile.WriteLine (as shown). Just make sure you set sLogFile at the top of the script.


Function DeleteFiles(objFolder)
	For	Each objFile in objFolder.Files
		On Error Resume Next
		If (Now() - objFile.DateLastModified) > intOldDate Then
			objFile.Delete
		End If
		if Err.Number = 0 then
			WriteToTxt GetDetails(objFile)
		end if
		On error Goto 0
	Next
End Function
 
Dim sLogFile
sLogFile = "C:\scripts\basiclog.txt"
 
Sub WriteToTxt(sText)
 
	Dim oFSO, oFile
	Set oFSO = CreateObject("Scripting.FileSystemObject")
	Set oFile = oFSO.OpenTextFile(sLogFile,8,True)
	oFile.WriteLine Now()&" "&sText
 
End Sub	

Open in new window

0
kerryhillAuthor Commented:
I apologize that it is taking a little while to respond, I am a little slow when it comes to asp script.  Thank you very much for the responses, I should be able to respond tomorrow about this.
0
boowhupCommented:
well spotted robincm, I think I pasted in a WIP.  it should have been this...

And robin's comment re changing from datelast modified / date last accessed is something to think about. Although If I remember correctly datelastmodifed is always later than datecreated and dateaccessed will be updated to now() as soon as it's touched by the filesystemobject??

I would leave it as datelastmodified, as that is the one that shows in windows explorer, and the one in a dos dir command - so would be the one you would manually compare against when testing the script.


strSearchFile = "common"
strBaseFolder = "d:\"
strdate = year(now) & month(now) & day(now)
strLogFile = ".\log-" & strdate & ".csv"
intOldDate = 45
'========================
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objBaseFolder = objFSO.GetFolder(strBaseFolder)
WriteToTxt "Time,Filename(Short),Filename(Full)"
ProcessFolder(objBaseFolder)
'=========================
 
Sub ProcessFolder(objFolder)
	On Error Resume Next
	For Each objSubFolder in objFolder.SubFolders
		For Each strExtension in arrDirectoryExtensions 
			if Instr(objSubFolder.Name,strSearchFile) then
				DeleteFiles(objSubFolder)
			end if
		Next
		ProcessFolder(objSubFolder)
	Next
	
	On Error Goto 0
End Sub
 
Function DeleteFiles(objFolder)
	For	Each objFile in objFolder.Files
		On Error Resume Next
		If (Now() - objFile.DateLastModified) > intOldDate Then
			objFile.Delete
		End If
		if Err.Number = 0 then
			WriteToTxt GetDetails(objFile)
		end if
		On error Goto 0
	Next
End Function
 
Function GetDetails(objF)
	GetDetails = objF.Path & "," & GetDetails 
	GetDetails = objF.Name & "," & GetDetails 	
End Function
 
Sub WriteToTxt(strWrite)
	'Appends lines to Log File
	Set FSO = CreateObject("Scripting.FileSystemObject")
	Set objOutputFile = FSO.OpenTextFile(strLogFile, 8, True)
	objOutputFile.WriteLine(Now & "," & strWrite)
	objOutputFile.close
End Sub

Open in new window

0
kerryhillAuthor Commented:
Ok, this is looking very nice, thank you, I may actually set it to createddate in the end because people will go in and modify stuff just to avoid it being deleted -- yeah, they would actually do that.  The other thing that happens is they bury the files in folders, is there a way for it to perform the delete recursively from the "common" folder?
0
kerryhillAuthor Commented:
Unfortunately, my scripting skills are truly non-existant, something I need to pick up, but is it already doing the recursive bit?  Is that this bit:  For Each objSubFolder in objFolder.SubFolders?
0
boowhupCommented:
At the moment it will only delete the folders in the "common" folder, not any files in subfolders, but it does check all subfolders for another common folder (thats the recursive part). If you want it to delete every file under the common folder, includng all files found in the subfolders (and their subfolders etc ) I can change it to do that. Do you want it to leave the empty subfolders behind, or delete those too?

0
kerryhillAuthor Commented:
Yes, I want it to leave the empty folders behind, but any folders under the common folder, it should delete all the files older than 45 days.
0
kerryhillAuthor Commented:
Boowhup,

I have tested this, and it works but I need it to delete the files recursively under each "common" folder it finds.  Is this possible?

0
boowhupCommented:
Sorry I have been a bit sick and overlooked this, hope you haven't been waiting too long.

I've changed the ProcessFolder subroutine to this....

Sub ProcessFolder(objFolder)
      On Error Resume Next
      For Each objSubFolder in objFolder.SubFolders
            if Instr(objSubFolder.Path,strSearchFile) then
                        DeleteFiles(objSubFolder)
                  end if
            ProcessFolder(objSubFolder)
      Next
      On Error Goto 0
End Sub

Have attached a full copy of the new code. Basically it's going to look for the word "common" in the whole path of the folder. (ie it will delete files from the following folders....)

c:\Username\common\
c:\username\common\subfolder1
c:\Username\common\subfolder2
c:\username\common\subfolder2\anothersubfolder

etc

This should work as you want, but best to do some testing 1st as always :D
strSearchFile = "common"
strBaseFolder = "d:\"
strdate = year(now) & month(now) & day(now)
strLogFile = ".\log-" & strdate & ".csv"
intOldDate = 45
'========================
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objBaseFolder = objFSO.GetFolder(strBaseFolder)
WriteToTxt "Time,Filename(Short),Filename(Full)"
ProcessFolder(objBaseFolder)
'=========================
 
Sub ProcessFolder(objFolder)
	On Error Resume Next
	For Each objSubFolder in objFolder.SubFolders
		if Instr(objSubFolder.Path,strSearchFile) then
				DeleteFiles(objSubFolder)
			end if
		ProcessFolder(objSubFolder)
	Next
	On Error Goto 0
End Sub
 
Function DeleteFiles(objFolder)
	For	Each objFile in objFolder.Files
		On Error Resume Next
		If (Now() - objFile.DateLastModified) > intOldDate Then
			objFile.Delete
		End If
		if Err.Number = 0 then
			WriteToTxt GetDetails(objFile)
		end if
		On error Goto 0
	Next
End Function
 
Function GetDetails(objF)
	GetDetails = objF.Path & "," & GetDetails 
	GetDetails = objF.Name & "," & GetDetails 	
End Function
 
Sub WriteToTxt(strWrite)
	'Appends lines to Log File
	Set FSO = CreateObject("Scripting.FileSystemObject")
	Set objOutputFile = FSO.OpenTextFile(strLogFile, 8, True)
	objOutputFile.WriteLine(Now & "," & strWrite)
	objOutputFile.close
End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kerryhillAuthor Commented:
Thank you so much, I hope you are feeling ok.  Don't feel bad at all about the time, you are helping me.  I just get the emails about needing to stay in touch, so I try to update my questions every few days.  I will test this tomorrow and get back to you.  Thanks again for all of your help, you have no idea how helpful this will be.
0
kerryhillAuthor Commented:
This works great!  Thank you very much!
0
kerryhillAuthor Commented:
Thank you very much this works!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.