Jump to content

Delete file by date function or script?


Eagle117
 Share

Recommended Posts

I am getting ready to write something for my company that will delete files from a few directories after they are 2 weeks old. I wanted to check and see if there was a function or a script that would do this for me automatically before I spend the time doing it myself. Anyone aware of something that can do this?

Link to comment
Share on other sites

Hello,

maybe try unixtools from http://unxutils.sourceforge.net/.

Find is your friend:

Using "find -mtime 14", you will get all files older than 14 days,

in all subdirectories. You might want to redirect the output to a file, and process it later.

Another possibility is to use rm from the tools:

"find -mtime +14 -exec rm {} ;"

will remove all files older than 14 days.

Play around with find to find out more. Find --help shows its switches.

ciao

Xandl

PS: one thing might be good to mention: be aware that this find tool is the same name as

windows find, residing in the path environment setting. So you can be in trouble quite easy.

In this case, I would use a batch file, and set a temp path like this test_dir.cmd:

setlocal
set path=D:\winprog\unixutil;%path%
find -mtime +14 -exec ls -l {};
endlocal
Edited by Xandl
Link to comment
Share on other sites

I modified my recursive file search to find the files to delete. I didn't actually write the deletion code, you should be able to figure it out.

#cs ----------------------------------------------------------------------------
        
         AutoIt Version: 3.2.10.0
         Author:         WeaponX
        
         Script Function:
            Recursive file search (array based, no redimensioning)
            
            Return files last modified 2 or more weeks ago
          
            Notes:
            -Second fastest by a slim margin (a few milliseconds)
        
    #ce ----------------------------------------------------------------------------
    
#include <array.au3>
#Include <Date.au3>
$timestamp = TimerInit()
$Array = RecursiveFileSearch(@ScriptDir, "", false)
MsgBox(0,"",(TimerDiff($timestamp) / 1000) & " seconds" & @CRLF & "# of files: " & $Array[0] & @CRLF & Ubound($Array));0.1063s / 2090 files
_ArrayDisplay($Array)
    
;startdir: Path to starting folder, without trailing slash
;RFSpattern: RegEx pattern to match
;RFSRecurse: Recurse subfolders, True / False
Func RecursiveFileSearch($startDir, $RFSpattern = ".", $RFSRecurse = true, $depth = 0)
  
    If $depth = 0 Then
        ;Get count of all files in subfolders
        $RFSfilecount = DirGetSize ($startDir,1)
        Global $RFSarray[$RFSfilecount[1] + 1]
        If StringRight($startDir, 1) <> "\" Then $startDir &= "\"
        $RFSarray[0] = 0
    EndIf
  
    $search = FileFindFirstFile($startDir & "*.*")
    If @error Then Return
  
    ;Search through all files and folders in directory
    While 1
        $next = FileFindNextFile($search)
        If @error Then ExitLoop
      
        ;If folder, recurse
        If StringInStr(FileGetAttrib($startDir & $next), "D") AND $RFSRecurse Then
            RecursiveFileSearch($startDir & $next, $RFSpattern, $depth + 1)
        Else
            ;Return file last modified time as array
            $filetime = FileGetTime ($startDir & $next, 0, 0)
            
            ;Return number of weeks since file was modified
            $diff = _DateDiff( 'w',$filetime[0] & "/" & $filetime[1] & "/" & $filetime[2] & " " & $filetime[3] & ":" & $filetime[4] & ":" & $filetime[5],_NowCalc())
            
            ;Only return files 2 weeks or older
            If StringRegExp($next,$RFSpattern, 0) AND $diff >= 2 Then
                ConsoleWrite($next & ": " & FileGetAttrib($startDir & $next) & " Age:" & $diff & @CRLF)    
                
                ;Append filename to array
                $RFSarray[$RFSarray[0] + 1] = $startDir & $next
                  
                ;Increment filecount
                $RFSarray[0] += 1
            EndIf
        EndIf
    WEnd
    FileClose($search)
  
    If $depth = 0 Then
        Redim $RFSarray[$RFSarray[0] + 1]
        Return $RFSarray
    EndIf
EndFunc
Link to comment
Share on other sites

Deletion code in a GUI

... Maybe you can use the search function from weapon

#include <GuiConstantsEx.au3>
#include <Date.au3>

; user input - maybe an array
; for $x.. blah, blah
$File_one = @WindowsDir & "\Notepad.exe"   ; older ?
$File_two = @WindowsDir & "\Notepad.exe"   ; newer ?
; next ..blah,blah

; GUI Based
$f = FileGetTime($File_one, 1)
$s = FileGetTime($File_two, 1)

; Create GUI
$hGUI = GUICreate("Compare File Time", 425, 300)
$iMemo = GUICtrlCreateEdit("", 2, 2, 420, 250, $WS_VSCROLL)
GUICtrlSetFont($iMemo, 9, 400, 0, "Courier New")
$delete = GUICtrlCreateButton("Replace File #1 with File #2 ", 40, 260, 150, 30)
GUICtrlSetState($delete, $GUI_DISABLE)
$next = GUICtrlCreateButton("Next", 240, 260, 150, 30)
GUISetState()

; Compare FAT Dates/Times
$tFileTime1 = _Date_Time_DosDateTimeToFileTime ($f[0] & "/" & $f[1] & "/" & $f[2], $f[3] & ":" & $f[4] & ":" & $f[5]) ; 01/01/2007 02:15:30
$tFileTime2 = _Date_Time_DosDateTimeToFileTime ($s[0] & "/" & $s[1] & "/" & $s[2], $s[3] & ":" & $s[4] & ":" & $s[5]) ; 12/31/2007 18:34:20
$pFiletime1 = DllStructGetPtr($tFileTime1)
$pFiletime2 = DllStructGetPtr($tFileTime2)

$result = _Date_Time_CompareFileTime ($pFiletime1, $pFiletime2)
If $result = 0 Then $result = "First file time is equal to second file time" 
If $result = 1 Then $result = "First file time is later than second file time" 
If $result = -1 Then $result = "First file time is earlier than second file time" 
$date_dif = _DateDiff('d', $f[2] & "/" & $f[1] & "/" & $f[0] & " " & $f[5] & ":" & $f[4] & ":" & $f[3], $s[2] & "/" & $s[1] & "/" & $s[0] & " " & $s[5] & ":" & $s[4] & ":" & $s[3])
GUICtrlSetData($iMemo, $result & @CRLF & "The days different is " & $date_dif & @CRLF, 1)

If $result = "First file time is earlier than second file time"  And $date_dif > 14 Then GUICtrlSetState($delete, $GUI_ENABLE)

; Loop until user exits
Do
    $msg = GUIGetMsg()
    
    If $msg = $delete Then
        ;FileDelete($File_one)
        ;FileCopy($File_two, $File_one, 1)
    EndIf
    If $msg = $next Then ExitLoop ; exit or returns to the file listed to an array
    
Until $msg = $GUI_EVENT_CLOSE

8)

NEWHeader1.png

Link to comment
Share on other sites

Hi

@WeaponX

Good func; but why modify your search?;

I would just make the array ,of all files in subfolders, usingy our FileList UDF, then loop through the array to decide the dates and which to delete?

@Val;

Looks good too; but aren't the new funcs redundant?

Why do you need "_Date_Time_DosDateTimeToFileTime" and "_Date_Time_CompareFileTime" when you are going to use "DateDiff" anyway?

Best, randall

Link to comment
Share on other sites

Hi

@WeaponX

Good func; but why modify your search?;

I would just make the array ,of all files in subfolders, usingy our FileList UDF, then loop through the array to decide the dates and which to delete?

@Val;

Looks good too; but aren't the new funcs redundant?

Why do you need "_Date_Time_DosDateTimeToFileTime" and "_Date_Time_CompareFileTime" when you are going to use "DateDiff" anyway?

Best, randall

Hey I just thought you needed a one trick pony.

Link to comment
Share on other sites

  • 4 weeks later...

I modified my recursive file search to find the files to delete. I didn't actually write the deletion code, you should be able to figure it out.

#cs ----------------------------------------------------------------------------
        
         AutoIt Version: 3.2.10.0
         Author:         WeaponX
        
         Script Function:
            Recursive file search (array based, no redimensioning)
            
            Return files last modified 2 or more weeks ago
          
            Notes:
            -Second fastest by a slim margin (a few milliseconds)
        
    #ce ----------------------------------------------------------------------------
    
#include <array.au3>
#Include <Date.au3>
$timestamp = TimerInit()
$Array = RecursiveFileSearch(@ScriptDir, "", false)
MsgBox(0,"",(TimerDiff($timestamp) / 1000) & " seconds" & @CRLF & "# of files: " & $Array[0] & @CRLF & Ubound($Array));0.1063s / 2090 files
_ArrayDisplay($Array)
    
;startdir: Path to starting folder, without trailing slash
;RFSpattern: RegEx pattern to match
;RFSRecurse: Recurse subfolders, True / False
Func RecursiveFileSearch($startDir, $RFSpattern = ".", $RFSRecurse = true, $depth = 0)
  
    If $depth = 0 Then
        ;Get count of all files in subfolders
        $RFSfilecount = DirGetSize ($startDir,1)
        Global $RFSarray[$RFSfilecount[1] + 1]
        If StringRight($startDir, 1) <> "\" Then $startDir &= "\"
        $RFSarray[0] = 0
    EndIf
  
    $search = FileFindFirstFile($startDir & "*.*")
    If @error Then Return
  
    ;Search through all files and folders in directory
    While 1
        $next = FileFindNextFile($search)
        If @error Then ExitLoop
      
        ;If folder, recurse
        If StringInStr(FileGetAttrib($startDir & $next), "D") AND $RFSRecurse Then
            RecursiveFileSearch($startDir & $next, $RFSpattern, $depth + 1)
        Else
            ;Return file last modified time as array
            $filetime = FileGetTime ($startDir & $next, 0, 0)
            
            ;Return number of weeks since file was modified
            $diff = _DateDiff( 'w',$filetime[0] & "/" & $filetime[1] & "/" & $filetime[2] & " " & $filetime[3] & ":" & $filetime[4] & ":" & $filetime[5],_NowCalc())
            
            ;Only return files 2 weeks or older
            If StringRegExp($next,$RFSpattern, 0) AND $diff >= 2 Then
                ConsoleWrite($next & ": " & FileGetAttrib($startDir & $next) & " Age:" & $diff & @CRLF)    
                
                ;Append filename to array
                $RFSarray[$RFSarray[0] + 1] = $startDir & $next
                  
                ;Increment filecount
                $RFSarray[0] += 1
            EndIf
        EndIf
    WEnd
    FileClose($search)
  
    If $depth = 0 Then
        Redim $RFSarray[$RFSarray[0] + 1]
        Return $RFSarray
    EndIf
EndFunc
what kind of magic do i need to get the depth variable working? i error out whenever i change the value from 0 to 5
Link to comment
Share on other sites

what kind of magic do i need to get the depth variable working? i error out whenever i change the value from 0 to 5

You don't set that variable. That is only used internally so the function know what recursion depth its at.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...