Need script to autodelete files after a certain period of time and logs the names of the deleted files with time and date.

Need script to autodelete files after a certain period of time and logs the names of the deleted files with time and date into a log file. Scriptlangauge doens't mind, but it has to be "nono friendly to edit" if time has to be adjusted or several dir's.
JSRhelpdeskAsked:
Who is Participating?
 
madison perkinsConnect With a Mentor Network AdministratorCommented:
Rem Script created: 13.02.2008 09:55
Rem Author: madisonp

strComputer = "." 'Script will run against local computer only.

'parameters you can change
strDirectory = "C:\temp" 'Directory scanned for files to be deleted
fileAge = 10 'age of files to be deleted
strLogFileName = "file.log" 'name of the log file

'Script starts here you can remove any of the comments that start with   '
'Creates the log file or opens the log file for appending
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set fsoObj = CreateObject("Scripting.FileSystemObject")
Set fileLog = FsoObj.OpenTextFile(strLogFileName,8,True)


'attaches to the WMI of strComputer.  Script not intended to run against
'remote computers.
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'Creates a list of files from the directory strDirectory
Set FileList = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='" & strDirectory & "'} Where " _
        & "ResultClass = CIM_DataFile")

'Checks if there were no files in the directory
If FileList.Count = 0 Then
    fileLog.Write (Date & " No files Found in directory.")
Else

'Compares the list of files last modified date against the current date and deletes files
'older than fileAge logging results in strLogFileName
fileCount = 0
For Each objFile in FileList
    If DateDiff("D", WMIDateStringToDate(objFile.LastModified), Now) > fileAge Then
        fileCount = fileCount + 1
        fileLog.Write objFile.Name
        fileLog.Write ", Modified Date: " & WMIDateStringToDate(objFile.LastModified)
        fileLog.WriteLine ", Date Deleted: " & Now
        objFile.Delete
    End If
Next
fileLog.WriteLine fileCount & " files deleted from " & strDirectory & " on " & Date & "'"
End If
'Closes the log file
fileLog.Close

' converts UTC to standard date and time
Function WMIDateStringToDate(dtmInstallDate)
    WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
        Mid(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
            & " " & Mid (dtmInstallDate, 9, 2) & ":" & _
                Mid(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, _
                    13, 2))
End Function
0
 
madison perkinsNetwork AdministratorCommented:
This should be pretty easy.  here is a basic delete all files from a directory and create a log file.
Rem Script created: 11.02.2008 11:18
Rem Author: madisonp

strComputer = "."

Const Forreading = 1, ForWriting = 2, ForAppending = 8
Set fsoObj = CreateObject("Scripting.FileSystemObject")
Set fileLog = FsoObj.OpenTextFile("file.log",8,True)

strDirectory = "C:\temp"


Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set FileList = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='" & strDirectory & "'} Where " _
        & "ResultClass = CIM_DataFile")
fileLog.WriteLine "File Name, " & "Creation Date, " & "Modified Date, " & "Accessed Date, "

if FileList.Count = 0 Then
    fileLog.Write (Date & "No files Found")
Else

For Each objFile In FileList
        fileLog.Write objFile.Name
        fileLog.Write ", "
        fileLog.Write WMIDateStringToDate(objFile.CreationDate)
        fileLog.Write ", "
        fileLog.Write WMIDateStringToDate(objFile.LastModified)
        fileLog.Write ", "
        fileLog.WriteLine WMIDateStringToDate(objFile.LastAccessed)
Next

fileLog.WriteLine Time & Date & " Error # " & CStr(Err.Number) & " " & Err.Description & " " & Err.Source

fileLog.Close

For Each objFile in FileList
    objFile.Delete
Next
End if
Function WMIDateStringToDate(dtmInstallDate)
    WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
        Mid(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
            & " " & Mid (dtmInstallDate, 9, 2) & ":" & _
                Mid(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, _
                    13, 2))
End Function
0
 
madison perkinsNetwork AdministratorCommented:
Copy from the first REM statement to the end function and past into a text file.  make sure you save it with a .vbs extention.  

it will look in the directory c:\temp and write the list of files to file.log then it deletes all files from the directory.  the file.log will be created in the directory that the script file resides.  change the directory that you will be deleteing files by modifying strDirectory.  it adds dates to the log file bases on creation, modification and access values of the file.   if there are no files in the directory it will log the date and input "no files found" in file.log.  the function at the end converts the time and date int a readable format.

If you add a little more info about what you are trying to accomplish i may be able to stream line it for you. for example you may not want the file create,modify access info in your file.log

i orignally wrote this script to look at the \windows\fonts directory on all my servers in a citrix farm and logged it to a file.  i added the delete part so it would accomplish what you wanted.

For Each objFile in FileList
    objFile.Delete
Next
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
BillDLCommented:
0
 
JSRhelpdeskAuthor Commented:
MADPERK: Thanks, this is almost what i like, what i do need extra is that the script looks for files of a surtain age (adjustable). All files uploaded in that directory should stay there like 10 days and then autodelete.

The function of the file attribs is nice, but for me i need te deletion date and time, so if a user misses a file we can see when it was uploaded and when deleted. I presume the log function adds logs and don't overwrite?

The vbs script can run once a day via scheduler?


BILLDL:
Thanks for your input, i see i can learn a lot from the scripts present, my vbs  programming scills are like none, zo i like to look at the scripts trying to understand how they work
0
 
madison perkinsNetwork AdministratorCommented:
OK will do.  I will revamp the script when i get off work tonight.  Was out sick yesterday wil the flu.
0
 
madison perkinsNetwork AdministratorCommented:
Yes the log file will append.

Do you have an internal mail server?  If you have something internal that you can relay off of without the need to authinticate i have a nice little email routine that can email you the previous days activity as well as append to the main log file.

Also what OS is the server that will hold the files/run the script?
0
 
JSRhelpdeskAuthor Commented:
MADPERK: Thanks, id like that! Flu? Yes, here its all around, everybody sick after a few spring days of sun.

It is on a win2003 server ENG, enailrelaying annonimous isnt allowed, but email is a bit to much, so no prob :)

Thanks again!

 
 
0
 
madison perkinsNetwork AdministratorCommented:
Just finished the script.  take a look and see what you think.  the log file is CSV so you can import into excel for easier reading. I added a bunch of comments so you can follow the logic.  

I used the LastModified date of the file to base the retention period.  
0
 
madison perkinsNetwork AdministratorCommented:
As before copy and paste into a text file saving it with a .vbs extention.  When you schedule the job on the local computer make sure the account you use to schedule has the proper access to delete the files, create and modify the log file and access the WMI name space.  If you don't want to use an Administrators account to schedule the job take a look at this article from Microsoft on WMI.  Q9 will give you the direction you need to add a user to the security section of WMI.  this script access root\CIMV2 section of WMI.  
0
 
JSRhelpdeskAuthor Commented:
Thanks, even some info so i can understand the script, great work! Here are the point for your kind work! Rowald
0
 
JSRhelpdeskAuthor Commented:
@ MADPERK:

Is this tool also optimimised to scan within maps in the directory?
0
 
madison perkinsNetwork AdministratorCommented:
I am not sure what is meant by "within maps in the directory"?
0
 
JSRhelpdeskAuthor Commented:
Sory, translation issue, i ment folders, now we see that several users make folders to store there upload files in. So is it possible to adjust the script to also look into subfolders?

example:
c:\temp (thats where the files are)
Users creat like: c:\temp\mydownload etc etc
0
 
madison perkinsNetwork AdministratorCommented:
yes.  

One question. do you want to keep the folder structure inside the root directory or would you prefer to remove the folder structure?

FYI it will probably be this weekend before i can get back to it.  Valentines supper with my girl friend tonight.
0
 
JSRhelpdeskAuthor Commented:
Hahaha, girl before work, thats the way it should be :)

No, if a folder is empty because all files are outdated and deleted the folder can be trashed also.
This weekend is no problem, i allready am in debt because of your work!

So have a nice valentine and we'll meet again

Rowald
0
 
madison perkinsNetwork AdministratorCommented:
FYI having problems reading more than two folders deep.  here is what i have so far. The script will delete all files in temp and all files in FolderA or FolderB but no files in A1 or B1.

Still working on it.

Start Folder C:\temp
directory Structure
C:\temp
            \FolderA
                         \FolderA1
            \FolderB
                         \FolderB1
     
0
 
madison perkinsNetwork AdministratorCommented:
Doh!

Never Mind.  It helps if my test files in the A1 and B1 directories were older than 10 days.

I revamped the script.  I combined what i had written perviously with something I found on the web over the weekend.

The script will look into the folder structure.  I have not tested it more than 3 levels deep.  It WILL NOT delete empty folders.   I haven't figured out how to do this yet. I dropped the WMI calls.  The script should now run on most OS's. There are only 3 places that you need to adjust, startFolder, strLogFileName and OlderThanDate. everything should be straight forward.

0
 
madison perkinsNetwork AdministratorCommented:
Rem Script created: 18.02.2008 10:49
Rem Author: madisonp

Rem Script created: 14.02.2008 09:33

Dim fso, startFolder, OlderThanDate
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
startFolder = "c:\temp" 'Starting Directory scanned for files to be deleted.
strLogFileName = "file.log" 'name of the log file.
OlderThanDate = DateAdd("d", -10, Date)  ' 10 days (adjust as necessary).

Set fsoObj = CreateObject("Scripting.FileSystemObject")
Set fileLog = FsoObj.OpenTextFile(strLogFileName,8,True)
force_cscript
DeleteOldFiles startFolder, OlderThanDate

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

   Set folder = fso.GetFolder(folderName)
   Set fileCollection = folder.Files
   For Each file In fileCollection
         If file.DateLastModified < BeforeDate Then
            fileLog.Write folderName & "\" & file.Name
            fileLog.WriteLine ", Date Deleted: " & Now
            fso.DeleteFile(file.Path)
         End If
   Next

    Set folderCollection = folder.SubFolders
    For Each subFolder In folderCollection
       DeleteOldFiles subFolder.Path, BeforeDate
    Next
End Function

'Force a cscript host


sub force_cscript
    dim args : args=""
    dim i, wshshell
    If right(lCase(wscript.fullname),11)= "wscript.exe" then
        for i=0 to wscript.arguments.count-1
            args = args & wscript.arguments(i) & " "
        next
        set wshshell=createobject("wscript.shell")
        wshshell.run wshshell.ExpandEnvironmentStrings("%comspec%") & _
            " /c cscript.exe //nologo """ & wscript.scriptfullname & """" & args    'change to /k for stay
        set wshshell=nothing
        wscript.quit
    end if
end sub

'Closes the log file
fileLog.Close
0
 
JSRhelpdeskAuthor Commented:
Hi there! Thanks again MADPERK, we will test this now. Unfortunatly i was sick last week.
0
 
JSRhelpdeskAuthor Commented:
MADPERK: The script runs as it should do...but..
If a user places a file back into a directory what was cleared by the script earlier, it wil get cleared again.

Example: in the directory WORK i created work.avi, after 10 days work.avi gets deleted. Now i make another work.avi and place it in the same directory WORK, the script runs the next day and deletes work.avi again... Is it possible to ad a scriptcode to delete empty folders after the 10 day files are shreded?
0
 
madison perkinsNetwork AdministratorCommented:
So they are moving a file that is more than 10 days old and the file gets deleted the next day or the file gets deleted 10 days after the file gets put back in the folder?

so you want to delete folders only if they are empty? - yes.  i found one that should work.  let me see what i need to do to trim it down a little bit and add it to your script.
'==================================== 
' VBScript Source File 
' NAME: DeleteEmptySubdirs.vbs 
' AUTHOR: Chay Harley 
' DATE  : v1.0: 28/10/2005  ; v1.1: 30/10/2005 ; v1.2 31/10/2005 
' Usage: 
'   cscript scriptname.vbs /d:C:\SomePath 
'   cscript scriptname.vbs /d:"C:\SomePath To Clean" 
'==================================== 
   Option Explicit 
 
   Dim WSHShell, RightMargin, LastParentFolder 
 
   Set WSHShell = CreateObject("Wscript.Shell") 
    
   If WScript.Arguments.Named.Count = 0 Then Usage() 
    
   Dim ExceptionList 
   'To exclude some folders, add to this list 
   ExceptionList = Array("Audio_TS", "My Documents", "My Pictures", "My Received Files") 
    
   Dim Path 
   Path = WScript.Arguments.Named.Item("D") 
   If Right(Path,1) <> "\" Then Path = Path & "\" 
   WScript.echo "Option [D]: " & UCase(Path) 
 
   Dim  objFSO, objRootFolder 
   Set objFSO = CreateObject("Scripting.FileSystemObject") 
    
   Set objRootFolder = objFSO.GetFolder(Path) 
   ProcessChildFolders objRootFolder 
    
   Sub ProcessingDirError(DirToCheck, ErrMsg) 
      'If we get 'permission denied', there is a read/delete block on the folder. Ignore it... 
      If ucase(ErrMsg) <> "PERMISSION DENIED" Then 
         WScript.Echo "Error [" & ErrMsg & "]. Please manually action """ & DirToCheck & """" 
      End if 
      Err.Clear 
   End Sub 
    
   Sub CheckAndDeleteEmptyFolder(objFolder) 
      On Error Resume Next 
      if objFolder.Size = 0 Then 
         If Err.Number Then 
            ProcessingDirError objFolder.Path, Err.Description 
         else          
            DeleteEmptyFolder objFolder, objFolder.Size 
         End If 
      End If 
   End Sub 
 
   Sub ProcessChildFolders(objRootFolder) 
      On Error Resume Next 
      Dim objParentFolder, objChildFolder 
      Set objParentFolder = objFSO.GetFolder(objRootFolder.Path) 
      If Err.Number Then 
         ProcessingDirError objRootFolder.Path, Err.Description 
      Else 
         If objParentFolder.SubFolders.Count > 0 Then 
            'process a folder branch 
            For Each objChildFolder In objParentFolder.SubFolders 
               ProcessChildFolders objChildFolder 
            Next 
            CheckAndDeleteEmptyFolder objParentFolder 
         Else 
            'Process a folder leaf (final folder) 
            if Left(objParentFolder.Path, InStr(InStr(objParentFolder.Path,"\")+1, objParentFolder.Path,"\")) <> LastParentFolder Then 
               WScript.Echo "[Progress] " & objParentFolder.Path 
            End If 
            CheckAndDeleteEmptyFolder objParentFolder 
            LastParentFolder = Left(objParentFolder.Path, InStr(InStr(objParentFolder.Path,"\")+1,objParentFolder.Path,"\")) 
         End If 
      End if 
   End Sub 
    
   Sub DeleteEmptyFolder(objDeleteFolder, FolderSize) 
      Dim ExceptionItem 
      For Each ExceptionItem In ExceptionList                     'skip exceptions ;) 
         If InStr(UCase(objDeleteFolder.Path),  Ucase(ExceptionItem)) Then 
            WScript.Echo "[Skipping] " & objDeleteFolder.Path 
            Exit Sub 
         End If 
      Next 
      DisplayDirectoryName objDeleteFolder.Path, FolderSize 
      Err.Clear 
      objDeleteFolder.Delete() 
      If Err.Number Then ProcessingDirError objDeleteFolder.Path, Err.Description 
   End Sub 
    
   Sub DisplayDirectoryName(DisplayPath, Size) 
      Dim TempNumber 
      TempNumber = Len(DisplayPath) 
      'set the right margin to make the output look good 
      If TempNumber >  RightMargin Then RightMargin = TempNumber 
      'yet, let's shift it back to the left if there's a huge difference (say, 30 chars) 
      If RightMargin - 30 > TempNumber Then RightMargin = TempNumber 
      WScript.Echo "*Deleting* " & DisplayPath & Space(RightMargin - TempNumber + 4 ) & "Size: " & Size 
   End Sub 
    
   Sub Usage() 
      WScript.Echo VbCrLf 
      WScript.Echo "=====================================" 
      WScript.Echo "Empty Folder/Directory Remover Script" 
      WScript.Echo "=====================================" 
      WScript.Echo VbCrLf & "Usage:" 
      WScript.Echo VbCrLf & " cscript scriptname.vbs /d:C:\SomePath " 
      WScript.Echo VbCrLf & " cscript scriptname.vbs /d:""C:\SomePath To Clean"" " 
      WScript.Quit 
   End Sub 

Open in new window

0
All Courses

From novice to tech pro — start learning today.