Jump to content

Recommended Posts

Posted

I would like help on coding something that detects the insertion of a USB drive(accomplished) and if it finds any exe files,then immediately ejects it.My purpose here is to prevent the entry of viruses(ravmon.exe,sal.xls.exe etc).Please Help.Thnx

Posted

Recursive File Search:

;
; RecurseDir()  v2.2
;
; Recursively search a directory structure for files matching a pattern
; and return its files as an array of file paths, the first value being the
; total number of file paths in the array (a-la "AutoIt Array").
;
; I spent some time testing many different routines. _GetFileList, by Jos van
; der Zande, always gave me the best results, and nicely coded, but around ten 
; times slower (52s) than Larry (and Beerman's) recursion routines (4.9s) when 
; recursing my home folder.**
;
; ** 1000 folders, 4773 files, 702MB. [cpu:1.3GHz, 640MB RAM] at time of writing
;
; This function is based on _GetFileList, but after a few hacks and tweaks is now
; more than fifteen times faster than the original.** The results are still as good, 
; but instead of 50+ seconds to recurse my home folder, it now takes 3.3 seconds, 
; making it fastest and bestest of all the AutoIt recursion routines! *tic*
;
; Note: you can now supply multiple file masks (needed for backup). It makes a lot 
; of sense to grab any other extensions while we are in a directory. 
; The delimiter is a comma..
;
;     RecurseDir("C:\Program Files", "*.reg,*.ini,*.cfg")
;
; When searching for multiple masks the speed improvements are *staggering*, and 
; logarithmic; basically multiply the number of masks. For instance, a backup of
; all the pref files in my Program Files folder is scanned, copied, zipped and 
; completed in around a minute. pretty good, considering it's over 12GB; all
; tools, no big game installs, and ten file masks to search.
;
; The optional third parameter "$dont_recurse" tells RecurseDir() to only return
; matches for files in the top level directory, no deeper. (true/false)
; see also ReadDir() above.
;
; You can also supply an optional fourth parameter which is a string; the path to
; a "dump file" to dump (log) the paths of all matched files; for debugging only,
; because it will slow things down some.
;
; In v2.2 you can also supply an optional fifth parameter, "$return_dirs" which
; will do exactly that, returning an AutoIt array of all the directories in the
; path, and *only* the directories. (true/false) 
;
; This function gets used a lot in my apps.
;
;
; **    A lot to do with using the "&=" operator. Those wee differences mount up.
;     Probably that operator wasn't available when the code was first written.
;
func RecurseDir($dir, $mask, $dont_recurse=false, $dump="", $return_dirs=false)
;debug(@ScriptLineNumber & ": " & "func: RecurseDir " & $dir)

   dim $n_dirnames[333333] ; maximum number of directories which can be scanned
   local $n_dircount = 0   ; ^ could be set much higher, if required
   local $n_file
   local $n_search
   local $n_tfile
   local $file_array
   local $filenames
   local $filecount
   local $dircount = 1
   local $msg = "error"

  ; if there was an "\" on the end of the given directory, remove that..
   if StringRight($dir, 1) = "\" then $dir = StringTrimRight($dir, 1)

   $n_dirnames[$dircount] = $dir

   if not FileExists($dir) then return 0

    while $dircount > $n_dircount; keep on looping until all directories are scanned..

        $n_dircount += 1
        $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\*.*")

        while 1 ; find all subdirs in this directory and store them in a array..
            $n_file = FileFindNextFile($n_search) 
            if @error then exitloop
           ; skip directory references..
            if $n_file = "." or $n_file = ".." then continueloop

            $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file

           ; if it's a directory, add it to the list of directories to be processed..
            if StringInStr(FileGetAttrib($n_tfile ), "D") and not $dont_recurse then                                
                $dircount += 1
                $n_dirnames[$dircount] = $n_tfile
            endif
        wend
        FileClose($n_search)

       ; multiple masks..
        if StringInStr($mask, ",", 2) then
            $mask_array = StringSplit($mask, ",")
        else; or else create a dummy array..
            dim $mask_array[2] = [1, $mask]
        endif

       ; loop through the array of masks..
        for $mask_c = 1 to $mask_array[0]
           ; find all files that match this mask..
            $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\" & $mask_array[$mask_c] )  
            if $n_search = -1 then continueloop

            while 1
                $n_file = FileFindNextFile($n_search) 
                if @error then exitloop; end of dir
                if $n_file = "." or $n_file = ".." then continueloop

                $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file
                if not StringInStr(FileGetAttrib( $n_tfile ), "D") then
                    $filecount += 1
                    $filenames &= $n_tfile & @LF
                endif
            wend
            FileClose($n_search)
        next
    wend

   ; flip to a string and back to remove extraneous entries
   ; this is quicker than redimming on every loop
    if $return_dirs then 
        $tmp_str = ""
        $i = 1
        while $n_dirnames[$i] <> ""
            $tmp_str &= $n_dirnames[$i] & "|"
            $i += 1
        wend
        $tmp_str = StringTrimRight($tmp_str, 1)
        $n_dirnames = StringSplit($tmp_str, "|")
        return $n_dirnames
    endif

    $filenames = StringTrimRight($filenames, 1)
    if $filenames = "" then return 0
    $file_array = StringSplit($filenames, @LF)

   ; dump results to a file..
    if $dump then 
        $dump_file = FileOpen($dump, 2)
        FileWrite($dump_file, $filenames)
        FileClose($dump_file)
    endif
    return($file_array)
endfunc
Posted

Hi,

Try this:

;#include <Array.au3> ;Only for _ArrayDisplay()

$USBDrive = "I:\"

$Results = _FileFind($USBDrive, "*.exe", 1)
If Not @Error Then ;Eject (oops, i don't realy know how to eject a USB drive ;) )

;_ArrayDisplay($Results)


;Flag = 1 search with recursive
;Flag = 0 search without recursive
;On Failure return @error as following:
;   1 - $sPath is not a dir or it not exists (in this case returned -1 as well).
;   2 - $sPath is empty dir.
;   3 - No files found in $sPath dir.
Func _FileFind($sPath, $Mask, $Flag=0)
    If Not StringInStr(FileGetAttrib($sPath), "D") Then Return SetError(1, 0, -1)
    
    Local $RetPathArr[1], $FindNextFile, $CurrentPath, $SubDirFindArr, $Ubound = 0
    If StringInStr($Mask, "*") Then $Mask = StringReplace($Mask, "*.", "")
    
    $sPath = StringRegExpReplace($sPath, '\\+ *$', '\')
    
    Local $FindFirstFile = FileFindFirstFile($sPath & "\*.*")
    If @error = 1 Then Return SetError(2, 0, 0)
    If $FindFirstFile = -1 Then Return SetError(3, 0, 0)
    
    While 1
        $FindNextFile = FileFindNextFile($FindFirstFile)
        If @error = 1 Then ExitLoop
        $CurrentPath = $sPath & "\" & $FindNextFile
        If $Flag = 1 And StringInStr(FileGetAttrib($CurrentPath), "D") Then
            $SubDirFindArr = _FileFind($CurrentPath, $Mask, $Flag)
            If IsArray($SubDirFindArr) Then
                For $i = 1 To UBound($SubDirFindArr)-1
                    $Ubound = UBound($RetPathArr)
                    ReDim $RetPathArr[$Ubound+1]
                    $RetPathArr[$Ubound] = $SubDirFindArr[$i]
                Next
            EndIf
        Else
            If $Mask = "*" Or $FindNextFile = $Mask Or StringRegExpReplace($CurrentPath, '^.*\.', '') = $Mask Then
                $Ubound = UBound($RetPathArr)
                ReDim $RetPathArr[$Ubound+1]
                $RetPathArr[$Ubound] = $CurrentPath
            EndIf
        EndIf
    WEnd
    FileClose($FindFirstFile)
    
    If $Ubound = 0 Then Return SetError(3, 0, 0)
    $RetPathArr[0] = $Ubound
    Return $RetPathArr
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Posted (edited)

Brett,

while using your code, can you write a simple way to delete all files found by RecurseDir function?

Thanks for your help!

Edited by SoulBlade
Posted

a simple way to delete all files found by RecurseDir function?

You just go for all element in the returned array (i am talking about my func)...

For $i = 1 To $Results[0]
      FileDelete($Results[$i])
Next

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Posted

thanks MsCreatoR.

I've managed to delete all files found by func RecurseDir.

Just add FileDelete($n_tfile) in this part of code:

CODE
; loop through the array of masks..

for $mask_c = 1 to $mask_array[0]

; find all files that match this mask..

$n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\" & $mask_array[$mask_c] )

if $n_search = -1 then continueloop

while 1

$n_file = FileFindNextFile($n_search)

if @error then exitloop; end of dir

if $n_file = "." or $n_file = ".." then continueloop

$n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file

FileDelete($n_tfile)

if not StringInStr(FileGetAttrib( $n_tfile ), "D") then

$filecount += 1

$filenames &= $n_tfile & @CRLF

endif

wend

FileClose($n_search)

next

wend

Any ideias to make RecurseDir find only folders?

Posted

For the Recursive Search Function,Is there any way that you can edit the function to return only a boolean value,true if it finds *.exe and false if no files are found,because i have no use of the path or name....Please Help...ThnX

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
  • Recently Browsing   0 members

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