Sign in to follow this  
Followers 0
johnmcloud

[SOLVED] Delete files older then x

46 posts in this topic

#1 ·  Posted (edited)

Hi guys,

I see many script for delete files older then x in this forum, i found this and i think is very useful:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7

_FilesOlder(@ScriptDir, "*.*", 7, 1) ; Look for wildcards in the Help file.
; _FilesOlder("DIRECTORY", "FILTER [Default *.*]", "NUMBER OF DAYS [Default 0]", "RECURSIVE SEARCH [Default 1 - Yes]")

Func _FilesOlder($sFilePath, $sFilter = "*.*", $iDate = 0, $iRecursive = 1)
    Local $aFilter, $sCommand = "del /q @path", $sDate = "", $sRecursive = ""
    $sFilePath = StringRegExpReplace($sFilePath, "[/]+z", "") & ""
    If $iDate > 0 Then
        $sDate = "/d -" & $iDate
    EndIf
    If $iRecursive Then
        $sRecursive = "/S"
    EndIf
    $aFilter = StringSplit($sFilter, ';')
    For $A = 1 To $aFilter[0]
        RunWait(@ComSpec & ' /c ' & 'forfiles /P ' & $sFilePath & ' ' & $sRecursive & ' /M ' & $aFilter[$A] & ' ' & $sDate & ' /C ' & ' "cmd /c ' & $sCommand & '"', $sFilePath, @SW_HIDE)
    Next
EndFunc   ;==>_FilesOlder

But for me not work, don't delete any files.

What is the problem?

Thanks

Edited by johnmcloud

Share this post


Link to post
Share on other sites



Try something like this

#include <Array.au3>
#include <Date.au3>
#include <File.au3>
;Root folder
$sourceFolder = @ScriptDir & 'Test'
;Gather files into an array
Global $fileList = __FileListToArrayEx($sourceFolder, "*.*");, 1, -1, True, True) ; 0 = files and folders
Global $found[1]
_ArrayDisplay($fileList)
;Loop through array
For $i = 1 To $fileList[0]
;Retrieve creation time of file
$Date = FileGetTime($fileList[$i], 0, 0) ; 0 modified, 1 = created
If @error Then Exit(1)
;Format date for use with Date UDF
$fDate = StringFormat("%s/%s/%s %s:%s:%s", $Date[0], $Date[1], $Date[2], $Date[3], $Date[4], $Date[5])
;Calculate age, remove files older than seven days
If _DateDiff('d', $fDate, _NowCalc()) > 7 Then ; the time
  If StringInStr(FileGetAttrib($fileList[$i]), 'D') Then
;~    DirRemove($sourceFolder, 1)
  Else
;~    FileDelete($sourceFolder & "" & $fileList[$i])
  EndIf
  _ArrayAdd($found, $fileList[$i])
  ConsoleWrite($fileList[$i] & ' deleted' & @CRLF)
Else
  ConsoleWrite('!' & $fileList[$i] & @CRLF)
EndIf
Next
$found[0] = UBound($found)
_ArrayDisplay($found, 'Deleted items')

; #FUNCTION# ====================================================================================================================
; Name...........: _FileListToArray
; Description ...: Lists files andor folders in a specified path (Similar to using Dir with the /B Switch)
; Syntax.........: _FileListToArray($sPath[, $sFilter = "*"[, $iFlag = 0 [, $sSDir = 0]]])
; Parameters ....: $sPath   - Path to generate filelist for.
;                 $sFilter - Optional the filter to use, default is *. (Multiple filter groups such as "*.png|*.jpg|*.bmp") Search the Autoit3 helpfile for the word "WildCards" For details.
;                 $iFlag   - Optional: specifies whether to return files folders or both
;                 |$iFlag=0(Default) Return both files and folders
;                 |$iFlag=1 Return files only
;                 |$iFlag=2 Return Folders only
;                 $sSDir   - Optional: specifies whether to return files folders or both
;                 |$sSDir=1 Search subdirectory
;                 |$sSDir=2 Search subdirectory & Return Full Path
; Return values .: @Error - 1 = Path not found or invalid
;                 |2 = Invalid $sFilter
;                 |3 = Invalid $iFlag
;                 |4 = No File(s) Found
; Author ........: SolidSnake <metalgx91 at="" gmail="" dot="" com="">
; Modified.......:
; Remarks .......: The array returned is one-dimensional and is made up as follows:
;                               $array[0] = Number of FilesFolders returned
;                               $array[1] = 1st FileFolder
;                               $array[2] = 2nd FileFolder
;                               $array[3] = 3rd FileFolder
;                               $array[n] = nth FileFolder
; Related .......:
; Link ..........:
; Example .......: Yes
; Note ..........: Special Thanks to Helge and Layer for help with the $iFlag update speed optimization by code65536, pdaughe
;                 Update By DXRW4E
; ===============================================================================================================================
Func __FileListToArrayEx($sPath, $sFilter = "*", $iFlag = 0, $sSDir = 0)
    Local $hSearch, $sFile, $sFileList, $sDelim = "|", $sSDirFTMP = $sFilter
    $sPath = StringRegExpReplace($sPath, "[/]+z", "") & "" ; ensure single trailing backslash
    If Not FileExists($sPath) Then Return SetError(1, 1, "")
    If StringRegExp($sFilter, "[/:><]|(?s)As*z") Then Return SetError(2, 2, "")
    If Not ($iFlag = 0 Or $iFlag = 1 Or $iFlag = 2) Then Return SetError(3, 3, "")
    $hSearch = FileFindFirstFile($sPath & "*")
    If @error Then Return SetError(4, 4, "")
    Local $hWSearch = $hSearch, $hWSTMP = $hSearch, $SearchWD, $FPath = StringRegExpReplace(StringRegExpReplace($sSDir, '[^2]+', ""), "2+", StringRegExpReplace($sPath, '', "")), $sSDirF[3] = [0, StringReplace($sSDirFTMP, "*", ""), "(?i)(" & StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace("|" & $sSDirFTMP & "|", '|h*|[|h]*', "|"), '[^$()+[]{},.=]', "$0"), "|([^*])", "|^$1"), "([^*])|", "$1$|"), '*', ".*"), '^|||$', "") & ")"]
    While 1
        $sFile = FileFindNextFile($hWSearch)
        If @error Then
            If $hWSearch = $hSearch Then ExitLoop
            FileClose($hWSearch)
            $hWSearch -= 1
            $SearchWD = StringLeft($SearchWD, StringInStr(StringTrimRight($SearchWD, 1), "", 1, -1))
        ElseIf $sSDir Then
            $sSDirF[0] = @extended
            If ($iFlag + $sSDirF[0] <> 2) Then
                If $sSDirF[1] Then
                    If StringRegExp($sFile, $sSDirF[2]) Then $sFileList &= $sDelim & $FPath & $SearchWD & $sFile
                Else
                    $sFileList &= $sDelim & $FPath & $SearchWD & $sFile
                EndIf
            EndIf
            If Not $sSDirF[0] Then ContinueLoop
            $hWSTMP = FileFindFirstFile($sPath & $SearchWD & $sFile & "*")
            If $hWSTMP = -1 Then ContinueLoop
            $hWSearch = $hWSTMP
            $SearchWD &= $sFile & ""
        Else
            If ($iFlag + @extended = 2) Or StringRegExp($sFile, $sSDirF[2]) = 0 Then ContinueLoop
            $sFileList &= $sDelim & $sFile
        EndIf
    WEnd
    FileClose($hSearch)
    If Not $sFileList Then Return SetError(4, 4, "")
    Return StringSplit(StringTrimLeft($sFileList, 1), "|")
EndFunc

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites

Seems good, i'll test it and let you know

Thanks

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Ok, i have test it, and i have two problem:

1) I'm using _RecFileListToArray, more easy for me, but i have the same problem also with _FileListToArrayEx

$InputExtension = GUICtrlCreateInput("*.*", 64, 78, 41, 21, $ES_CENTER)

$Dir = GUICtrlRead($FolderInput)
$Ext = '"' & GUICtrlRead($InputExtension) & '"'
Global $fileList = _RecFileListToArray($Dir, $Ext, 1, $SubFolder, 0, 1, "", "")
Global $found[1]
_ArrayDisplay($fileList)
;Loop through array
For $i = 1 To $fileList[0]

Give me error:

==> Subscript used with non-Array variable.:
For $i = 1 To $fileList[0]
For $i = 1 To $fileList^ ERROR
>Exit code: 1   Time: 3.236

If i make, with the same folder, this:

$Dir = GUICtrlRead($FolderInput)
Global $fileList = _RecFileListToArray($Dir, "*.*", 1, $SubFolder, 0, 1, "", "")
Global $found[1]
_ArrayDisplay($fileList)
;Loop through array
For $i = 1 To $fileList[0]

Work, but i need to read it into the GUI ( if need i'll post it )

2) If i select a folder with only files ( example C: or C:Program Files ), i have only the "Array: List view Display", and when i close it, the script close with this error code ( and without the list of delete item ):

>Exit code: 1   Time: 3.236

And don't delete file if i uncomment them in the script, so not work if the dir has only files

Thanks for support

Edited by johnmcloud

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <Array.au3>
#include <Date.au3>
#include <File.au3>
#include <RecFileListToArray.au3> ; External UDF
 
$GUI1 = GUICreate("Test", 270, 207, -1, -1)
$LabelFolder = GUICtrlCreateLabel("Select folder", 8, 8, 96, 17)
$FolderInput = GUICtrlCreateInput("", 8, 24, 185, 21)
$ButtonFolder = GUICtrlCreateButton("...", 202, 23, 49, 23)
$CheckboxSubFolder = GUICtrlCreateCheckbox("Checkbox", 8, 48, 16, 16)
$LabelSubFolder = GUICtrlCreateLabel("Include Subfiles", 24, 49, 95, 17)
$LabelDelete = GUICtrlCreateLabel("Delete files", 8, 80, 53, 17)
$InputExtension = GUICtrlCreateInput("*.*", 64, 78, 41, 21, $ES_CENTER)
$LabelOldFiles = GUICtrlCreateLabel("older then", 110, 80, 64, 17)
$Days = GUICtrlCreateInput("15", 176, 78, 41, 21, $ES_CENTER)
$LabelDays = GUICtrlCreateLabel("days", 223, 80, 29, 17)
$ButtonDelete = GUICtrlCreateButton("delete", 13, 159, 243, 33)
$RadioModify = GUICtrlCreateRadio("Radio", 155, 114, 16, 25)
$LabelModify = GUICtrlCreateLabel("Modify Date", 172, 120, 80, 17)
$RadioCreate = GUICtrlCreateRadio("Radio", 8, 114, 16, 25)
GUICtrlSetState(-1, $GUI_CHECKED)
$LabelCreate = GUICtrlCreateLabel("Created Date", 25, 120, 87, 17)
$Group1 = GUICtrlCreateGroup("", 2, 104, 265, 41)
GUICtrlCreateGroup("", -99, -99, 1, 1)
$Group2 = GUICtrlCreateGroup("", 2, 144, 265, 57)
GUICtrlCreateGroup("", -99, -99, 1, 1)
$Group3 = GUICtrlCreateGroup("", 2, 0, 265, 105)
GUICtrlCreateGroup("", -99, -99, 1, 1)
GUISetState(@SW_SHOW)

While 1
$nMsg = GUIGetMsg()
Switch $nMsg
  Case $GUI_EVENT_CLOSE
   Exit
  Case $ButtonFolder
   Select_Folder()
  Case $ButtonDelete
   Delete_Files()
EndSwitch
WEnd

FUNC Select_Folder()
    $Dir = FileSelectFolder("Select a folder...", "", 0, @WorkingDir)
    If @error Then
MsgBox(16, "Error", "No folder")
Return
EndIf
If StringRight($Dir, 1) <> "" Then $Dir &= ""
    If $Dir <> "" Then
GUICtrlSetData($FolderInput,$Dir)
EndIf
EndFunc
 
Func Delete_Files()
If GUICtrlRead($CheckboxSubFolder) = $GUI_CHECKED Then
Local $SubFolder = 1
Else
Local $SubFolder = 0
EndIf

If GUICtrlRead($RadioCreate) = $GUI_CHECKED Then
Local $Check = 1 ; Set by Date
Else
Local $Check = 0 ; Set Modify
EndIf

If GUICtrlRead($FolderInput) = "" Then
MsgBox(16, "Error", "No folder")
Return
EndIf
 
If GUICtrlRead($InputExtension) = "" Then
MsgBox(16, "Error", "No extesion")
Return
EndIf

Local $Folder, $FileList, $FileType = GUICtrlRead($InputExtension), $Days = GUICtrlRead($Days)
$Folder = GUICtrlRead($FolderInput)
If @error Then
MsgBox(16, "Error", "no file in that folder")
Return
EndIf

$FileList = _RecFileListToArray($Folder, $FileType, 1, $SubFolder, 0, 1, "", "")
If @error Then
MsgBox(16, 'Error', "no file" & " " & GUICtrlRead($InputExtension) & " " & "in the directory:" & @LF & $Folder)
Return
EndIf
For $i = $FileList[0] To 1 Step -1
    Local $FileDate = FileGetTime($Folder & '' & $FileList[$i], $Check, 0)
    If IsArray($FileDate) Then
        Local $Date = $FileDate[0] & '/' & $FileDate[1] & '/' & $FileDate[2] & ' ' & $FileDate[3] & ':' & $FileDate[4] & ':' & $FileDate[5]
        If _DateDiff('D', $Date, _NowCalc()) >= $Days Then ContinueLoop
    EndIf
    _ArrayDelete($FileList, $i)
Next
If UBound($FileList) - 1 = 0 Then Exit MsgBox(270352, 'Information', 'no files' & " " & GUICtrlRead($InputExtension) & " " & "in:" & @LF & $Folder)
$FileList[0] = UBound($FileList) - 1
_ArrayDisplay($FileList, 'File list')
Local $Confirm = MsgBox(270628, 'Information', 'Continue to delete?')
Select
    Case $Confirm = 6 ;Yes
        For $i = 1 To $FileList[0]
            FileRecycle($Folder & '' & $FileList[$i])
        Next
    Case $Confirm = 7 ;No
EndSelect
EndFunc

Someone can test it? I think not work properly

If i change days and creation/modify date i see always the same number of file

Thanks

Edited by johnmcloud

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

I'm a little confused.

Don't you want to delete the files that are more than $Days days old?

You'r currently making a list of the files that are *not* older than $Days.

Also, _ArrayDelete() is a performance killer if you're calling it repeatedly.

You could try replacing the one loop in your script with the following, that creates a list to delete without using _ArrayDelete():

Global $DeleteList[$FileList[0] + 1], $DeleteCount, $FileDate, $Date

For $i = 1 to $FileList[0]
    $FileDate = FileGetTime($Folder & '' & $FileList[$i], $Check, 0), $Date
    If IsArray($FileDate) Then
        $Date = $FileDate[0] & '/' & $FileDate[1] & '/' & $FileDate[2] & ' ' & $FileDate[3] & ':' & $FileDate[4] & ':' & $FileDate[5]
        If _DateDiff('D', $Date, _NowCalc()) >= $Days Then
            $DeleteCount += 1
            $DeleteList[$DeleteCount] = $FileList[$i]
        EndIf
    EndIf
Next
_ArrayDisplay($DeleteList, 'Delete list')
Edited by Spiff59

Share this post


Link to post
Share on other sites

Yes, i want to delete files older the X days, but i have problem also with your script, for be sure about it can you post it into mine?

Share this post


Link to post
Share on other sites

forfiles /S /M *.pdf /D -7 /C "cmd /c del @path@file"

Deletes all PDF files under the current path older than 7 days.

The forfiles tool can be found in the Windows (2000 ?) Resource kit tools.


Regards,Hannes[spoiler]If you can't convince them, confuse them![/spoiler]

Share this post


Link to post
Share on other sites

forfiles /S /M *.pdf /D -7 /C "cmd /c del @path@file"

Deletes all PDF files under the current path older than 7 days.

The forfiles tool can be found in the Windows (2000 ?) Resource kit tools.

Thanks for suggestion, it was my first idea ( look at first post ) ;)

I think someone in the forum can help me to do this in "original" AutoIT style :)

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

Yes, i want to delete files older the X days, but i have problem also with your script, for be sure about it can you post it into mine?

Favor done.

Now you have to promise to say "older than" instead of "older then" for the rest of your life!

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
;#include <Array.au3>
#include <Date.au3>
#include <File.au3> ; testing
;#include <RecFileListToArray.au3> ; External UDF

$GUI1 = GUICreate("Test", 270, 207, -1, -1)
GUICtrlCreateGroup("", 2, 0, 265, 105)
GUICtrlCreateLabel("Select folder", 8, 8, 96, 17)
$FolderInput = GUICtrlCreateInput("", 8, 24, 185, 21)
$ButtonFolder = GUICtrlCreateButton("...", 202, 23, 49, 23)
$CheckboxSubFolder = GUICtrlCreateCheckbox("Checkbox", 8, 48, 16, 16)
GUICtrlCreateLabel("Include Subfolders", 24, 49, 95, 17)
GUICtrlCreateLabel("Delete ", 8, 80, 32, 17)
$InputExtension = GUICtrlCreateInput("*.*", 48, 78, 41, 21, $ES_CENTER)
GUICtrlCreateLabel("files older than", 96, 80, 80, 17)
$InputDays = GUICtrlCreateInput("15", 175, 78, 41, 21, $ES_CENTER)
GUICtrlCreateLabel("days", 223, 80, 29, 17)
GUICtrlCreateGroup("", -99, -99, 1, 1)
GUICtrlCreateGroup("", 2, 104, 265, 41)
$RadioCreated = GUICtrlCreateRadio(" Created Date", 8, 114, 100, 25)
GUICtrlSetState(-1, $GUI_CHECKED)
$RadioModified = GUICtrlCreateRadio(" Modified Date", 155, 114, 100, 25)
GUICtrlCreateGroup("", -99, -99, 1, 1)
GUICtrlCreateGroup("", 2, 144, 265, 57)
$ButtonDelete = GUICtrlCreateButton("delete", 13, 159, 243, 33)
GUICtrlCreateGroup("", -99, -99, 1, 1)
GUISetState(@SW_SHOW)

While 1
$nMsg = GUIGetMsg()
Switch $nMsg
  Case $GUI_EVENT_CLOSE
   Exit
  Case $ButtonFolder
   Select_Folder()
  Case $ButtonDelete
   Delete_Files()
EndSwitch
WEnd

FUNC Select_Folder()
    $Dir = FileSelectFolder("Select a folder...", "", 0, @WorkingDir)
    If @error Then
  MsgBox(16, "Error", "No folder")
  Return
EndIf
If StringRight($Dir, 1) <> "" Then $Dir &= ""
    If $Dir <> "" Then GUICtrlSetData($FolderInput,$Dir)
EndFunc

Func Delete_Files()
Local $Folder, $FileType, $Days, $SubFolder, $Check, $FileList, $FileDate, $Date, $Confirm
$SubFolder = (GUICtrlRead($CheckboxSubFolder) = $GUI_CHECKED)
$Check = (GUICtrlRead($RadioCreated) = $GUI_CHECKED)
If GUICtrlRead($FolderInput) = "" Then
  MsgBox(16, "Error", "No folder")
  Return
EndIf
If GUICtrlRead($InputExtension) = "" Then
  MsgBox(16, "Error", "No extesion")
  Return
EndIf
$Folder = GUICtrlRead($FolderInput)
If @error Then
  MsgBox(16, "Error", "no file in that folder")
  Return
EndIf
$FileType = GUICtrlRead($InputExtension)
$Days = GUICtrlRead($InputDays)
; $FileList = _RecFileListToArray($Folder, $FileType, 1, $SubFolder, 0, 1, "", "")
$FileList = _FileListToArray($Folder, $FileType, 1) ; testing
If @error Then
  MsgBox(16, 'Error', "no file" & " " & GUICtrlRead($InputExtension) & " " & "in the directory:" & @LF & $Folder)
  Return
EndIf
; _ArrayDisplay($FileList, 'File list')

Local $DeleteList[$FileList[0] + 1], $DeleteCount
For $i = 1 to $FileList[0]
  $FileDate = FileGetTime($Folder & '' & $FileList[$i], $Check, 0)
  If IsArray($FileDate) Then
   $Date = $FileDate[0] & '/' & $FileDate[1] & '/' & $FileDate[2] & ' ' & $FileDate[3] & ':' & $FileDate[4] & ':' & $FileDate[5]
   If _DateDiff('D', $Date, _NowCalc()) >= $Days Then
    $DeleteCount += 1
    $DeleteList[$DeleteCount] = $FileList[$i]
   EndIf
  EndIf
Next
$DeleteList[0] = $DeleteCount
Redim $DeleteList[$DeleteCount + 1]
; _ArrayDisplay($DeleteList, 'Delete list')
If $DeleteList[0] = 0 Then Exit MsgBox(270352, 'Information', 'No ' & $FileType & " files to delete in " & $Folder)
$Confirm = MsgBox(270628, 'Information', 'Continue to delete?')
Select
  Case $Confirm = 6 ;Yes
   For $i = 1 To $DeleteList[0]
;   FileRecycle($Folder & '' & $FileList[$i])
    ToolTip("Deleting: " & $Folder & '' & $DeleteList[$i]) ; testing
    Sleep(200) ; testing
   Next
  Case $Confirm = 7 ;No
EndSelect
EndFunc
Edited by Spiff59

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

Not work, man :)

I don't have touch anything, just select "Desktop" folder, give me error *.* not found ( i have files on desktop ), click OK and exit with error code 1

EDIT: I'm doing some change to the code...if i have problem i'll post

Edited by johnmcloud

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

Finally the code working fine :)

My last thing is use a progress bar on file size, based only on file list of files to delete. I have used so:

$size = DirGetSize($DeleteList[0])
  MsgBox(0, "", "Size(MegaBytes):" & Round($size / 1024 / 1024))

The result is always 0. How is the problem?

Thanks to all guys who help me ;)

Edited by johnmcloud

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

Maybe you need to switch between DirGetSize and FileGetSize.

Or the [0] element of your array is the count of elements and not a path. Then you'll need a loop and $i instead of [0] and maybe start with $i = 1 instead of 0 when it is the elements count.

Edited by Xenobiologist

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

I have make this:

$size = FileGetSize($DeleteList[0])
MsgBox(0, "", "Size(MegaBytes):" & Round($size / 1024 / 1024))

Same result = 0

Do you mean like this?

For $i = 1 to $DeleteList[0]
$size = FileGetSize($DeleteList[$i])
MsgBox(0, "", "Size(MegaBytes):" & Round($size / 1024 / 1024))
Next

I have multiple MsgBox with Result = 0

Edited by johnmcloud

Share this post


Link to post
Share on other sites

Did you read my complete post? I guess the element 0 contains the number of elements and not a valid path.

Try a consolewrite before executing the command and read the post above :-)


Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

You have right, the [0] is only the number, and the [1] is only the name of the file without full path.

What must I do to have the full path of the files to be deleted?

I have change the _RecFileListToArray for include full path of the file:

$FileList = _RecFileListToArray($Folder, $FileType, 1, $SubFolder, 0, 2, "", "")

But give me error at this:

If $DeleteList[0] = 0 Then
  MsgBox(270352, "Information", "no file" & $FileType & " in directory:" & @LF & $Folder)
Edited by johnmcloud

Share this post


Link to post
Share on other sites

I need some more information. What error?

Can you strip your code down and post it so that I can test it?


Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites

#18 ·  Posted (edited)

Sure, the error is the MsgBox, no file found

This is the part of the script:

$FileType = GUICtrlRead($InputExtension)
$Days = GUICtrlRead($InputDays)
$FileList = _RecFileListToArray($Folder, $FileType, 1, $SubFolder, 0, 2, "", "")
If @error Then
  MsgBox(16, 'Error', "No file" & " " & GUICtrlRead($InputExtension) & " " & "in the directory:" & @LF & $Folder)
  Return
EndIf

Local $DeleteList[$FileList[0] + 1], $DeleteCount
For $i = 1 to $FileList[0]
  $FileDate = FileGetTime($Folder & '' & $FileList[$i], 1, 0)
  If IsArray($FileDate) Then
   $Date = $FileDate[0] & '/' & $FileDate[1] & '/' & $FileDate[2] & ' ' & $FileDate[3] & ':' & $FileDate[4] & ':' & $FileDate[5]
   If _DateDiff('D', $Date, _NowCalc()) >= $Days Then
    $DeleteCount += 1
    $DeleteList[$DeleteCount] = $FileList[$i]
   EndIf
  EndIf
Next

$LogCreate = FileOpen(@TempDir & "log.txt", 1)
$Log = @TempDir & "log.txt"
_FileWriteFromArray($LogCreate, $DeleteList)
FileClose($LogCreate)
_FileWriteToLine($Log, 1, "File List to delete:", 0)

$DeleteList[0] = $DeleteCount
Redim $DeleteList[$DeleteCount + 1]

If $DeleteList[0] = 0 Then
  MsgBox(16, "Error", "No file " & $FileType & " in directory:" & @LF & $Folder)
  FileDelete(@TempDir & "log.txt")
  Return
Else
  MsgBox(64, "Information", "OK")
  EndIf
Edited by johnmcloud

Share this post


Link to post
Share on other sites

I needed to change a little to test it.

Here is a version.

#Region    ;************ Includes ************
#include-once
#Include <GUIConstantsEx.au3>
#Include <Date.au3>
#Include <File.au3>
#Include <Array.au3>
#EndRegion ;************ Includes ************
$FileType = "*.au3";GUICtrlRead($InputExtension)
$Days = 1;GUICtrlRead($InputDays)
$Folder = 'c:AutoitForumTestsTest'
$FileList = _RecFileListToArray($Folder, $FileType);, 1, 1, 0, 2, "", "")
If @error Then
MsgBox(16, 'Error', "No file" & " " & "GUICtrlRead($InputExtension)" & " " & "in the directory:" & @LF & $Folder)
;~  Return
EndIf
$Check = 1
_ArrayDisplay($FileList, 'FOUND')
Local $str = ''
For $i = 1 To $FileList[0]
$FileDate = FileGetTime($Folder & '' & $FileList[$i], $Check, 0)
If IsArray($FileDate) Then
  $Date = $FileDate[0] & '/' & $FileDate[1] & '/' & $FileDate[2] & ' ' & $FileDate[3] & ':' & $FileDate[4] & ':' & $FileDate[5]
  ConsoleWrite(_DateDiff('D', $Date, _NowCalc()) & @LF)
  If _DateDiff('D', $Date, _NowCalc()) >= $Days Then
   $str &= $FileList[$i] & '|'
  EndIf
EndIf
Next
Local $DeleteList = StringSplit(StringTrimRight($str, 1), '|')
_ArrayDisplay($DeleteList)
;~ $LogCreate = FileOpen(@TempDir & "log.txt", 1)
;~ $Log = @TempDir & "log.txt"
;~ _FileWriteFromArray($LogCreate, $DeleteList)
;~ FileClose($LogCreate)
;~ _FileWriteToLine($Log, 1, "File List to delete:", 0)
If $DeleteList[0] = 0 Then ; THIS IS DANGEROUS, WHEN THERE ISN'T AN ARRAY CREATED!!!!
MsgBox(16, "Error", "No file " & $FileType & " in directory:" & @LF & $Folder)
FileDelete(@TempDir & "log.txt")
;~  Return
Else
;~  _ReadText()
MsgBox(64, "Information", "OK")
;~  GUICtrlSetState($ButtonDelete, $GUI_ENABLE)
EndIf

;#AutoIt3Wrapper_au3check_parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
; #INDEX# =======================================================================================================================
; Title .........: _RecFileListToArray
; AutoIt Version : v3.3.1.1 or higher
; Language ......: English
; Description ...: Lists files andor folders in specified path with optional recursion to defined level and result sorting
; Note ..........:
; Author(s) .....: Melba23
; Remarks .......: - Modified Array.au3 functions - credit: Jos van der Zande, LazyCoder, Tylo, Ultima, SolidSnake and gcriaco
;                 - SRE patterns - credit: various forum members and Spiff59 in particular
;                 - Despite the name, this UDF is iterative, not recursive
; ===============================================================================================================================
; #CURRENT# =====================================================================================================================
; _RecFileListToArray: Lists files andor folders in a specified path with optional recursion to defined level and result sorting
; ===============================================================================================================================
; #INTERNAL_USE_ONLY#============================================================================================================
; _RFLTA_ListToMask ......; Convert include/exclude lists to SRE format
; _RFLTA_AddToList .......; Add element to list which is resized if necessary
; _RFLTA_AddFileLists ....; Add internal lists after resizing and optional sorting
; _RFLTA_FileListSearch ..; Search file match list for files associated with a folder
; _RFLTA_ArraySort .......; Wrapper for QuickSort function
; _RFLTA_QuickSort .......: Recursive array sort
; _RFLTA_ArrayConcatenate : Join 2 arrays
; ===============================================================================================================================
; #FUNCTION# ====================================================================================================================
; Name...........: _RecFileListToArray
; Description ...: Lists files andor folders in a specified path with optional recursion to defined level and result sorting
; Syntax.........: _RecFileListToArray($sPath[, $sInclude_List = "*"[, $iReturn = 0[, $iRecur = 0[, $iSort = 0[, $iReturnPath = 1[, $sExclude_List = ""[, $sExclude_List_Folder]]]]]]])
; Parameters ....: $sPath - Initial path used to generate filelist.  If path ends in  then folders will be returned with an ending 
;                 $sInclude_List - Optional: filter for included results (default "*"). Multiple filters must be separated by ";"
;                 $iReturn - Optional: specifies whether to return files, folders or both
;                 |$iReturn = 0 - Return both files and folders (Default)
;                                 If non-recursive Include/Exclude_List applies to files and folders
;                                 If recursive Include/Exclude_List applies to files only, all folders are searched unless excluded using $sExclude_List_Folder
;                 |$iReturn = 1 - Return files only    - Include/Exclude_List applies to files only, all folders searched if recursive
;                 |$iReturn = 2 - Return folders only  - Include/Exclude_List applies to folders only for searching and return
;                 $iRecur - Optional: specifies whether to search recursively in subfolders and to what level
;                 |$iRecur = 1 - Search in all subfolders (unlimited recursion)
;                 |$iRecur = 0 - Do not search in subfolders (Default)
;                 |$iRecur = Negative integer - Search in subfolders to specified depth
;                 $iSort - Optional: sort ordered in alphabetical and depth order
;                 |$iSort = 0 - Not sorted (Default)
;                 |$iSort = 1 - Sorted
;                 |$iSort = 2 - Sorted with faster algorithm (assumes files sorted within each folder - requires NTFS drive)
;                 $iReturnPath - Optional: specifies displayed path of results
;                 |$iReturnPath = 0 - File/folder name only
;                 |$iReturnPath = 1 - Relative to initial path (Default)
;                 |$iReturnPath = 2 - Full path included
;                 $sExclude_List - Optional: filter for excluded results (default ""). Multiple filters must be separated by ";"
;                 $sExclude_List_Folder - Optional: only used if $iReturn = 0 AND $iRecur = 1 to exclude folders matching the filter
; Requirement(s).: v3.3.1.1 or higher
; Return values .: Success: One-dimensional array made up as follows:
;                 |$array[0] = Number of FilesFolders returned
;                 |$array[1] = 1st FileFolder
;                 |$array[2] = 2nd FileFolder
;                 |...
;                 |$array[n] = nth FileFolder
;    Failure: Null string and @error = 1 with @extended set as follows:
;                 |1 = Path not found or invalid
;                 |2 = Invalid $sInclude_List
;                 |3 = Invalid $iReturn
;                 |4 = Invalid $iRecur
;                 |5 = Invalid $iSort
;                 |6 = Invalid $iReturnPath
;                 |7 = Invalid $sExclude_List
;                 |8 = Invalid $sExclude_List_Folder
;                 |9 = No files/folders found
; Author ........: Melba23
; Remarks .......: Compatible with existing _FileListToArray syntax
; Related .......:
; Link ..........;
; Example .......; Yes
; ===============================================================================================================================
Func _RecFileListToArray($sInitialPath, $sInclude_List = "*", $iReturn = 0, $iRecur = 0, $iSort = 0, $iReturnPath = 1, $sExclude_List = "", $sExclude_List_Folder = "")
Local $asReturnList[100] = [0], $asFileMatchList[100] = [0], $asRootFileMatchList[100] = [0], $asFolderMatchList[100] = [0], $asFolderSearchList[100] = [1]
Local $sFolderSlash = "", $iMaxLevel, $sInclude_File_Mask, $sExclude_File_Mask, $sInclude_Folder_Mask = ".+", $sExclude_Folder_Mask = ":"
Local $hSearch, $fFolder, $sRetPath = "", $sCurrentPath, $sName
Local $asFolderFileSectionList[100][2] = [[0, 0]], $sFolderToFind, $iFileSectionStartIndex, $iFileSectionEndIndex
; Check for valid path
If Not FileExists($sInitialPath) Then Return SetError(1, 1, "")
; Check if folders should have trailing  and ensure that initial path does have one
If StringRight($sInitialPath, 1) = "" Then
  $sFolderSlash = ""
Else
  $sInitialPath = $sInitialPath & ""
EndIf
; Add path to folder search list
$asFolderSearchList[1] = $sInitialPath
; Check for valid recur value
If $iRecur > 1 Or Not IsInt($iRecur) Then Return SetError(1, 4, "")
; If required, determine  count for max recursive level setting
If $iRecur < 0 Then
  StringReplace($sInitialPath, "", "", 2)
  $iMaxLevel = @extended - $iRecur
EndIf
; Create Include mask for files
If $sInclude_List = "*" Then
  $sInclude_File_Mask = ".+"
Else
  If Not _RFLTA_ListToMask($sInclude_File_Mask, $sInclude_List) Then Return SetError(1, 2, "")
EndIf
; Set Include mask for folders
Switch $iReturn
  Case 0
   ; Folders affected by mask if not recursive
   Switch $iRecur
    Case 0
     ; Folders match mask for compatibility
     $sInclude_Folder_Mask = $sInclude_File_Mask
    ;Case Else
     ; All folders match
   EndSwitch
  ;Case 1
   ; All folders match
  Case 2
   ; Folders affected by mask
   $sInclude_Folder_Mask = $sInclude_File_Mask
EndSwitch
; Create Exclude List mask for files
If $sExclude_List = "" Then
  $sExclude_File_Mask = ":" ; Set unmatchable mask
Else
  If Not _RFLTA_ListToMask($sExclude_File_Mask, $sExclude_List) Then Return SetError(1, 7, "")
EndIf
; Set Exclude mask for folders
Switch $iReturn
  Case 0
   ; Folders affected by mask if not recursive
   Switch $iRecur
    Case 0
     ; Folders match mask for compatibility
     $sExclude_Folder_Mask = $sExclude_File_Mask
    Case Else
     ; Exclude defined folders as set in extended
     If $sExclude_List_Folder <> "" Then
      If Not _RFLTA_ListToMask($sExclude_Folder_Mask, $sExclude_List_Folder) Then Return SetError(1, 8, "")
     EndIf
   EndSwitch
  ;Case 1
   ; All folders match
  Case 2
   ; Folders affected by normal mask
   $sExclude_Folder_Mask = $sExclude_File_Mask
EndSwitch
; Verify other parameters
If Not ($iReturn = 0 Or $iReturn = 1 Or $iReturn = 2) Then Return SetError(1, 3, "")
If Not ($iSort = 0 Or $iSort = 1 Or $iSort = 2) Then Return SetError(1, 5, "")
If Not ($iReturnPath = 0 Or $iReturnPath = 1 Or $iReturnPath = 2) Then Return SetError(1, 6, "")
; Search within listed folders
While $asFolderSearchList[0] > 0
  ; Set path to search
  $sCurrentPath = $asFolderSearchList[$asFolderSearchList[0]]
  ; Reduce folder search list count
  $asFolderSearchList[0] -= 1
  ; Determine return path to add to file/folder name
  Switch $iReturnPath
   ; Case 0 ; Name only
   ; Leave as ""
   Case 1 ;Relative to initial path
    $sRetPath = StringReplace($sCurrentPath, $sInitialPath, "")
   Case 2 ; Full path
    $sRetPath = $sCurrentPath
  EndSwitch
  ; Get search handle
  $hSearch = FileFindFirstFile($sCurrentPath & "*")
  ; If sorting files and folders with paths then store folder name and position of associated files in list
  If $iReturn = 0 And $iSort And $iReturnPath Then
   _RFLTA_AddToList($asFolderFileSectionList, $sRetPath, $asFileMatchList[0] + 1)
  EndIf
  ; If folder empty move to next in list
  If $hSearch = -1 Then
   ContinueLoop
  EndIf
  ; Search folder
  While 1
   $sName = FileFindNextFile($hSearch)
   ; Check for end of folder
   If @error Then
    ExitLoop
   EndIf
   ; Set subfolder flag - @extended set in 3.3.1.1 +
   $fFolder = @extended
   ; If folder then check whether to add to search list
   If $fFolder Then
    Select
     Case $iRecur < 0 ; Check recur depth
      StringReplace($sCurrentPath, "", "", 0, 2)
      If @extended < $iMaxLevel Then
       ContinueCase ; Check if matched to masks
      EndIf
     Case $iRecur = 1 ; Full recur
      If Not StringRegExp($sName, $sExclude_Folder_Mask) Then ; Add folder unless excluded
        _RFLTA_AddToList($asFolderSearchList, $sCurrentPath & $sName & "")
      EndIf
     ; Case $iRecur = 0 ; Never add
      ; Do nothing
    EndSelect
   EndIf
   If $iSort Then ; Save in relevant folders for later sorting
    If $fFolder Then
     If StringRegExp($sName, $sInclude_Folder_Mask) And Not StringRegExp($sName, $sExclude_Folder_Mask) Then
      _RFLTA_AddToList($asFolderMatchList, $sRetPath & $sName & $sFolderSlash)
     EndIf
    Else
     If StringRegExp($sName, $sInclude_File_Mask) And Not StringRegExp($sName, $sExclude_File_Mask) Then
      ; Select required list for files
      If $sCurrentPath = $sInitialPath Then
       _RFLTA_AddToList($asRootFileMatchList, $sRetPath & $sName)
      Else
       _RFLTA_AddToList($asFileMatchList, $sRetPath & $sName)
      EndIf
     EndIf
    EndIf
   Else ; Save directly in return list
    If $fFolder Then
     If $iReturn <> 1 And StringRegExp($sName, $sInclude_Folder_Mask) And Not StringRegExp($sName, $sExclude_Folder_Mask) Then
      _RFLTA_AddToList($asReturnList, $sRetPath & $sName & $sFolderSlash)
     EndIf
    Else
     If $iReturn <> 2 And StringRegExp($sName, $sInclude_File_Mask) And Not StringRegExp($sName, $sExclude_File_Mask) Then
      _RFLTA_AddToList($asReturnList, $sRetPath & $sName)
     EndIf
    EndIf
   EndIf
  WEnd
  ; Close current search
  FileClose($hSearch)
WEnd
If $iSort Then
  ; Check if any file/folders have been added depending on required return
  Switch $iReturn
   Case 0 ; If no folders then number of files is immaterial
    If $asRootFileMatchList[0] = 0 And $asFolderMatchList[0] = 0 Then Return SetError(1, 9, "")
   Case 1
    If $asRootFileMatchList[0] = 0 And $asFileMatchList[0] = 0 Then Return SetError(1, 9, "")
   Case 2
    If $asFolderMatchList[0] = 0 Then Return SetError(1, 9, "")
  EndSwitch
  Switch $iReturn
   Case 2 ; Folders only
    ; Correctly size folder match list
    ReDim $asFolderMatchList[$asFolderMatchList[0] + 1]
    ; Copy size folder match array
    $asReturnList = $asFolderMatchList
    ; Simple sort list
    _RFLTA_ArraySort($asReturnList)
   Case 1 ; Files only
    If $iReturnPath = 0 Then ; names only so simple sort suffices
     ; Combine file match lists
     _RFLTA_AddFileLists($asReturnList, $asRootFileMatchList, $asFileMatchList)
     ; Simple sort combined file list
     _RFLTA_ArraySort($asReturnList)
    Else
     ; Combine sorted file match lists
     _RFLTA_AddFileLists($asReturnList, $asRootFileMatchList, $asFileMatchList, 1)
    EndIf
   Case 0 ; Both files and folders
    If $iReturnPath = 0 Then ; names only so simple sort suffices
     ; Combine file match lists
     _RFLTA_AddFileLists($asReturnList, $asRootFileMatchList, $asFileMatchList)
     ; Set correct count for folder add
     $asReturnList[0] += $asFolderMatchList[0]
     ; Resize and add file match array
     ReDim $asFolderMatchList[$asFolderMatchList[0] + 1]
     _RFLTA_ArrayConcatenate($asReturnList, $asFolderMatchList)
     ; Simple sort final list
     _RFLTA_ArraySort($asReturnList)
    Else
     ; Size return list
     Local $asReturnList[$asFileMatchList[0] + $asRootFileMatchList[0] + $asFolderMatchList[0] + 1]
     $asReturnList[0] = $asFileMatchList[0] + $asRootFileMatchList[0] + $asFolderMatchList[0]
     ; Sort root file list
     _RFLTA_ArraySort($asRootFileMatchList, 1, $asRootFileMatchList[0])
     ; Add the sorted root files at the top
     For $i = 1 To $asRootFileMatchList[0]
      $asReturnList[$i] = $asRootFileMatchList[$i]
     Next
     ; Set next insertion index
     Local $iNextInsertionIndex = $asRootFileMatchList[0] + 1
     ; Sort folder list
     _RFLTA_ArraySort($asFolderMatchList, 1, $asFolderMatchList[0])
     ; Work through folder list
     For $i = 1 To $asFolderMatchList[0]
      ; Format folder name for search
      If $sFolderSlash Then
       $sFolderToFind = $asFolderMatchList[$i]
      Else
       $sFolderToFind = $asFolderMatchList[$i] & ""
      EndIf
      ; Find folder in FolderFileSectionList
      For $j = 1 To $asFolderFileSectionList[0][0]
       If $sFolderToFind = $asFolderFileSectionList[$j][0] Then ExitLoop
      Next
      ; Set file list indexes
      $iFileSectionStartIndex = $asFolderFileSectionList[$j][1]
      If $j = $asFolderFileSectionList[0][0] Then
       $iFileSectionEndIndex = $asFileMatchList[0]
      Else
       $iFileSectionEndIndex = $asFolderFileSectionList[$j + 1][1] - 1
      EndIf
      ; Sort files if required
      If $iSort = 1 Then
       _RFLTA_ArraySort($asFileMatchList, $iFileSectionStartIndex, $iFileSectionEndIndex)
      EndIf
      ; Add folder to return list
      $asReturnList[$iNextInsertionIndex] = $asFolderMatchList[$i]
      $iNextInsertionIndex += 1
      ; Add files to return list
      For $j = $iFileSectionStartIndex To $iFileSectionEndIndex
       $asReturnList[$iNextInsertionIndex] = $asFileMatchList[$j]
       $iNextInsertionIndex += 1
      Next
     Next
    EndIf
  EndSwitch
Else ; No sort
  ; Check if any file/folders have been added
  If $asReturnList[0] = 0 Then Return SetError(1, 9, "")
  ; Remove any unused return list elements from last ReDim
  ReDim $asReturnList[$asReturnList[0] + 1]
EndIf
Return $asReturnList

EndFunc   ;==>_RecFileListToArray
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_ListToMask
; Description ...: Convert include/exclude lists to SRE format
; Syntax ........: _RFLTA_ListToMask(ByRef $sMask, $sList)
; Parameters ....: $asMask - Include/Exclude mask to create
;                 $asList - Include/Exclude list to convert
; Return values .: Success: 1
;                 Failure: 0
; Author ........: SRE patterns developed from those posted by various forum members and Spiff59 in particular
; Remarks .......: This function is used internally by _RecFileListToArray
; ===============================================================================================================================
Func _RFLTA_ListToMask(ByRef $sMask, $sList)
; Check for invalid characters within list
If StringRegExp($sList, "|/|:|<|>||") Then Return 0
; Strip WS and insert | for ;
$sList = StringReplace(StringStripWS(StringRegExpReplace($sList, "s*;s*", ";"), 3), ";", "|")
; Convert to SRE pattern
$sList = StringReplace(StringReplace(StringRegExpReplace($sList, "[][$^.{}()+-]", "$0"), "?", "."), "*", ".*?")
; Add prefix and suffix
$sMask =  "(?i)^(" & $sList & ")z"
Return 1
EndFunc   ;==>_RFLTA_ListToMask
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_AddToList
; Description ...: Add element to [?] or [?][2] list which is resized if necessary
; Syntax ........: _RFLTA_AddToList(ByRef $asList, $vValue_0, [$vValue_1])
; Parameters ....: $aList - List to be added to
;                 $vValue_0 - Value to add (to [0] element in [?][2] array if $vValue_1 exists)
;                 $vValue_1 - Value to add to [1] element in [?][2] array (optional)
; Return values .: None - array modified ByRef
; Author ........: Melba23
; Remarks .......: This function is used internally by _RecFileListToArray
; ===============================================================================================================================
Func _RFLTA_AddToList(ByRef $aList, $vValue_0, $vValue_1 = -1)
If $vValue_1 = -1 Then ; [?] array
  ; Increase list count
  $aList[0] += 1
  ; Double list size if too small (fewer ReDim needed)
  If UBound($aList) <= $aList[0] Then ReDim $aList[UBound($aList) * 2]
  ; Add value
  $aList[$aList[0]] = $vValue_0
Else ; [?][2] array
  $aList[0][0] += 1
  If UBound($aList) <= $aList[0][0] Then ReDim $aList[UBound($aList) * 2][2]
  $aList[$aList[0][0]][0] = $vValue_0
  $aList[$aList[0][0]][1] = $vValue_1
EndIf
EndFunc   ;==>_RFLTA_AddToList
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_AddFileLists
; Description ...: Add internal lists after resizing and optional sorting
; Syntax ........: _RFLTA_AddFileLists(ByRef $asTarget, $asSource_1, $asSource_2[, $iSort = 0])
; Parameters ....: $asReturnList - Base list
;                 $asRootFileMatchList - First list to add
;                 $asFileMatchList - Second list to add
;                 $iSort - (Optional) Whether to sort lists before adding
;                 |$iSort = 0 (Default) No sort
;                 |$iSort = 1 Sort in descending alphabetical order
; Return values .: None - array modified ByRef
; Author ........: Melba23
; Remarks .......: This function is used internally by _RecFileListToArray
; ===============================================================================================================================
Func _RFLTA_AddFileLists(ByRef $asTarget, $asSource_1, $asSource_2, $iSort = 0)
; Correctly size root file match array
ReDim $asSource_1[$asSource_1[0] + 1]
; Simple sort root file match array if required
If $iSort = 1 Then _RFLTA_ArraySort($asSource_1)
; Copy root file match array
$asTarget = $asSource_1
; Add file match count
$asTarget[0] += $asSource_2[0]
; Correctly size file match array
ReDim $asSource_2[$asSource_2[0] + 1]
; Simple sort file match array if required
If $iSort = 1 Then _RFLTA_ArraySort($asSource_2)
; Add file match array
_RFLTA_ArrayConcatenate($asTarget, $asSource_2)
EndFunc   ;==>_RFLTA_AddFileLists
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_FileListSearch
; Description ...: Search file array for beginning and end indices of folder associated files
; Syntax ........: _RFLTA_FileListSearch(Const ByRef $avArray, $vValue)
; Parameters ....: $avArray - Array to search ($asFileMatchList)
;                 $vValue  - Value to search for (Folder name from $asFolderMatchList)
;                 $iIndex  - Index to begin search (search down from here - and then from here to top if not found)
;                 $sSlash  -  if folder names end in  - else empty string
; Return values .: Success: Array holding top and bottom indices of folder associated files
;                 Failure: Returns -1
; Author ........: Melba23
; Modified.......:
; Remarks .......: This function is used internally by _RecFileListToArray
; ===============================================================================================================================
Func _RFLTA_FileListSearch(Const ByRef $avArray, $vValue, $iIndex, $sSlash)
Local $aRet[2]
; Add final  if required
If Not $sSlash Then $vValue &= ""
; Start by getting top match - search down from start index
For $i = $iIndex To $avArray[0]
  ; SRE gives path less filename
  If StringRegExpReplace($avArray[$i], "(^.*)(.*)", "1") = $vValue Then ExitLoop
Next
If $i > $avArray[0] Then
  ; No match found so look from start index upwards
  If $iIndex = $avArray[0] Then $iIndex -= 1
  For $i = $iIndex + 1 To 1 Step -1
   If StringRegExpReplace($avArray[$i], "(^.*)(.*)", "1") = $vValue Then ExitLoop
  Next
  ; If still no match - return " nothing found" for empty folder
  If $i = 0 Then Return SetError(1, 0, "")
  ; Set index of bottom file
  $aRet[1] = $i
  ; Now look for top match
  For $i = $aRet[1] To 1 Step -1
   If StringRegExpReplace($avArray[$i], "(^.*)(.*)", "1") <> $vValue Then ExitLoop
  Next
  ; Set top match
  $aRet[0] = $i + 1
Else
  ; Set index of top associated file
  $aRet[0] = $i
  ; Now look for bottom match - find first file which does not match
  For $i = $aRet[0] To $avArray[0]
   If StringRegExpReplace($avArray[$i], "(^.*)(.*)", "1") <> $vValue Then ExitLoop
  Next
  ; Set bottom match
  $aRet[1] = $i - 1
EndIf
Return $aRet
EndFunc   ;==>_RFLTA_FileListSearch
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_ArraySort
; Description ...: Wrapper for QuickSort function
; Syntax ........: _RFLTA_ArraySort(ByRef $avArray)
; Parameters ....: $avArray - Array to sort
;                 $iStart  - Index to start sort
;                 $iEnd    - Index to end sort
; Return values .: None - array modified ByRef
; Author ........: Jos van der Zande, LazyCoder, Tylo, Ultima
; Modified.......: Melba23
; Remarks .......: This function is used internally by _RecFileListToArray
; ===============================================================================================================================
Func _RFLTA_ArraySort(ByRef $avArray, $iStart = 1, $iEnd = -99)
If $iEnd = -99 Then $iEnd = UBound($avArray) - 1
_RFLTA_QuickSort($avArray, $iStart, $iEnd)
EndFunc   ;==>_RFLTA_ArraySort
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_QuickSort
; Description ...: Recursive array sort
; Syntax ........: _RFLTA_QuickSort(ByRef $avArray, ByRef $iStart, ByRef $iEnd)
; Parameters ....: $avArray - Array to sort in descending alphabetical order
;                 $iStart - Start index
;                 $iEnd - End index
; Return values .: None - array modified ByRef
; Author ........: Jos van der Zande, LazyCoder, Tylo, Ultima
; Modified.......: Melba23
; Remarks .......: This function is used internally by _RFLTA_ArraySort
; ===============================================================================================================================
Func _RFLTA_QuickSort(ByRef $avArray, ByRef $iStart, ByRef $iEnd)
Local $vTmp
If ($iEnd - $iStart) < 15 Then
  Local $i, $j, $vCur
  For $i = $iStart + 1 To $iEnd
   $vTmp = $avArray[$i]
   If IsNumber($vTmp) Then
    For $j = $i - 1 To $iStart Step -1
     $vCur = $avArray[$j]
     If ($vTmp >= $vCur And IsNumber($vCur)) Or (Not IsNumber($vCur) And StringCompare($vTmp, $vCur) >= 0) Then ExitLoop
     $avArray[$j + 1] = $vCur
    Next
   Else
    For $j = $i - 1 To $iStart Step -1
     If (StringCompare($vTmp, $avArray[$j]) >= 0) Then ExitLoop
     $avArray[$j + 1] = $avArray[$j]
    Next
   EndIf
   $avArray[$j + 1] = $vTmp
  Next
  Return
EndIf
Local $L = $iStart, $R = $iEnd, $vPivot = $avArray[Int(($iStart + $iEnd) / 2)], $fNum = IsNumber($vPivot)
Do
  If $fNum Then
   While ($avArray[$L] < $vPivot And IsNumber($avArray[$L])) Or (Not IsNumber($avArray[$L]) And StringCompare($avArray[$L], $vPivot) < 0)
    $L += 1
   WEnd
   While ($avArray[$R] > $vPivot And IsNumber($avArray[$R])) Or (Not IsNumber($avArray[$R]) And StringCompare($avArray[$R], $vPivot) > 0)
    $R -= 1
   WEnd
  Else
   While (StringCompare($avArray[$L], $vPivot) < 0)
    $L += 1
   WEnd
   While (StringCompare($avArray[$R], $vPivot) > 0)
    $R -= 1
   WEnd
  EndIf
  If $L <= $R Then
   $vTmp = $avArray[$L]
   $avArray[$L] = $avArray[$R]
   $avArray[$R] = $vTmp
   $L += 1
   $R -= 1
  EndIf
Until $L > $R
_RFLTA_QuickSort($avArray, $iStart, $R)
_RFLTA_QuickSort($avArray, $L, $iEnd)
EndFunc   ;==>_RFLTA_QuickSort
; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _RFLTA_ArrayConcatenate
; Description ...: Joins 2 arrays
; Syntax ........: _RFLTA_ArrayConcatenate(ByRef $avArrayTarget, Const ByRef $avArraySource)
; Parameters ....: $avArrayTarget - Base array
;                 $avArraySource - Array to add from element 1 onwards
; Return values .: None - array modified ByRef
; Author ........: Ultima
; Modified.......: Melba23
; Remarks .......: This function is used internally by _RecFileListToArray
; ===============================================================================================================================
Func _RFLTA_ArrayConcatenate(ByRef $avArrayTarget, Const ByRef $avArraySource)
Local $iUBoundTarget = UBound($avArrayTarget) - 1, $iUBoundSource = UBound($avArraySource)
ReDim $avArrayTarget[$iUBoundTarget + $iUBoundSource]
For $i = 1 To $iUBoundSource - 1
  $avArrayTarget[$iUBoundTarget + $i] = $avArraySource[$i]
Next
EndFunc   ;==>_RFLTA_ArrayConcatenate

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

I have test it and we have always the same problem, the path is relative and work:

$FileList = _RecFileListToArray($Folder, $FileType, 1, $SubFolder, 0, 1, "", "")

List file to delete:
11
Au3Check.dat
Au3Check.exe
Au3Info.exe
Au3Info_x64.exe
AutoIt v3 Website.url
AutoIt.chm
AutoIt3.chm
AutoIt3.exe
AutoIt3Help.exe
AutoIt3_x64.exe
UDFs3.chm

With full path not work:

$FileList = _RecFileListToArray($Folder, $FileType, 1, $SubFolder, 0, 2, "", "")

List file to delete:
1

Maybe i can make a progress bar on number of file ( with a little help ;) ), insted checking the size of the all file. What do you think?

And why you have make this for dangerous

If $DeleteList[0] = 0 Then ; THIS IS DANGEROUS, WHEN THERE ISN'T AN ARRAY CREATED!!!!

You have an alternative? Thanks for your time :)

Edited by johnmcloud

Share this post


Link to post
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
Sign in to follow this  
Followers 0

  • Similar Content

    • MarkBe
      By MarkBe
      Hi
      I am trying to check a number of applications are up to date and install the update if required. This will run as a shutdown script, pushed out through Group Policy.
      I am querying various registry keys to determine if
      The software is actually installed The software is at the correct version Once the need for update is determined then it calls another function to run the update.
      If the software is up to date or not installed, it moves down to the next software section which changes the registry key variables and calls the registry query function again
      I have managed to get the function for (un)installs to work but I am having trouble with the registry query function
      #NoTrayIcon #include <AutoItConstants.au3> #include <MsgBoxConstants.au3> #include <FileConstants.au3> ; Here we go! ;########################################################################################################## ;Declare variables Global $RegKey86, $RegKey64, $RegValueName, $RegValueData, $CheckVersion86, $CheckVersion64 ; 7Zip ;########################################################################################################## _7Zip_Function() Func _7Zip_Function() ; Registry location and values that are checked for current software version ; Ensure the x64 key is preceeded with 'HKLM64' $RegKey86="HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip" $RegKey64="HKLM64\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip" $RegValueName="DisplayVersion" $RegValueData="16.04" ; Excecution ; --------------------------------------------------------------------------------------------------------- If _CheckSW() = 1 Then _UninstallOldVer() _InstallSW() EndIf EndFunc ;==>_7Zip_Function ; Functions ;########################################################################################################## Func _CheckSW() $CheckVersion86=RegRead ($RegKey86, $RegValueName) $CheckVersion64=RegRead ($RegKey64, $RegValueName) If $CheckVersion86=$RegValueData Or $CheckVersion64=$RegValueData Then Return 0 ElseIf $CheckVersion86="" And $CheckVersion64="" Then Return 0 Else Return 1 EndIf EndFunc ;==>CheckSW  
    • WoodGrain
      By WoodGrain
      Hi guys,
      Could someone please tell me what I'm doing wrong with this code?
      I'm trying to take user input and then run a function with the same name, but it's not calling the function.
      So in the below after pressing Shift+F8 I would enter the text (without quotes) "testFunc".
      As you can see I've also tried this with IF statements, I'm new to using Switch/Case.
      HotKeySet("+{F8}", RunManually) Func RunManually() ;Use a case statement with 1 hot key and an InputBox to manually run functions $funcName = InputBox("Which Func to Run?", "Enter the name of the function to run") MsgBox(0, "Entered value", $funcName) ;If $funcName = testFunc Then testFunc() ;If $funcName = test2Func Then test2Func() Switch $funcName Case testFunc MsgBox(0, "Calling", "Calling Function") testFunc() MsgBox(0, "Called", "Function call finished") Case test2Func MsgBox(0, "Calling", "Calling Function") test2Func() MsgBox(0, "Called", "Function call finished") EndSwitch EndFunc While 1 ;testFunc() Sleep(1000) WEnd Func testFunc() MsgBox(0, "func running", "Seems to work!") EndFunc Func test2Func() MsgBox(0, "func 2 running", "2 Seems to work!") EndFunc Thanks!
    • TheOnlyOne
      By TheOnlyOne
      So currently I have some code waiting for a status to change(there is different indicators to check if this status has changed) 
      Func oneRow($count) $globaltimer = _Timer_SetTimer($gui, 60000*10, "reset") $errTimer = TimerInit() While (1)         If PixelGetColor(1117, 326) = 0xC6C6C6 Then ExitLoop (1)         Sleep(500)         MouseClick("right")         Sleep(600)         If PixelGetColor(1117, 326) = 0xC6C6C6 Then ExitLoop (1)         If TimerDiff($errTimer) > 5000 Then             If PixelGetColor(1100, 310) = 0x707070 Or PixelGetColor(901, 305) = 0xE0E0E0 Or PixelGetColor(1043, 383) = 0xC6C6C6 Then                 Sleep(100)                 Send("{esc}")                 Sleep(1000)             EndIf         EndIf     WEnd .... EndFunc   ;==>oneRow The two timers is for error checking. This works just fine the problem comes when I go into the while 1 loop, my hotkeys at the top of the program seems to stop working, for an example 
      HotKeySet("{f1}", "stop") Func stop() Exit EndFunc ;==>stop Does not work at all after the while loop. The globaltimer is never called even though i tried setting the delay all the way down to 3 seconds. So I thought that maybe one of the function I use is blocking so the timer would never be called/the hotkey wouldn't work? if i make an delay just before the while loop the hotkey works just fine. Oh and the errTimer is supossed to not reset after 5 seconds but should keep making the check it does if five seconds have passed
    • alongsnake
      By alongsnake
      The best example is MouseClick, where you have MouseClick($Button, [$x, $y, [..........]]) Where if X is set, Y must be set too.
      I do know how to make it so that X and Y are optional, but I am not sure how to get Y mandatory if X is set. I did check the help, but didn't see anything there.
      Thanks in advance
    • TheDcoder
      By TheDcoder
      <snip>
      Hello , This time my script is throwing an error which does not make sense... How can I fix this?
      Code Snippet from the screenshot:
       
       
       P.S You saw it right, I am making a small handy tool for AutoIt Coders, TD