Что нового

Cкрипт для поиска файла на разных носителях

TERMINAL

Новичок
Сообщения
18
Репутация
1
Помогите найти скрипт для поиска файла на разных носителях.
В данном случае есть только такой скрипт
Код:
Opt("GuiOnEventMode", 1)

Global $Progress = 0.1, $GetPath = 0
$PathForSearch = @HomeDrive
$FileToFind = "test.au3"

$Gui = GUICreate("File Finder", 300, 170, -1, -1, -1, 0x00000088)
GUISetOnEvent(-3, "ExitScript")

GUICtrlCreateLabel("Path to search on:", 20, 30)
$PathInput = GUICtrlCreateInput($PathForSearch, 20, 50, 270)

GUICtrlCreateLabel("File to find:", 20, 90)
$FileNameInput = GUICtrlCreateInput($FileToFind, 20, 110, 270)

$SearchButton = GUICtrlCreateButton("Search", 70, 140, 60, 20)
GUICtrlSetOnEvent(-1, "SearchButton")
$CancelButton = GUICtrlCreateButton("Cancel", 180, 140, 60, 20)
GUICtrlSetOnEvent(-1, "ExitScript")

GUISetState()

While 1
    Sleep(100)
WEnd

Func _FindFile($Path, $FileName)
    $ModPath = $Path & "\*" ; Формирую строку поиска (толко для инициализации)
    $File = FileFindFirstFile($ModPath) ; Инициализация поиска
    While 1
        ; Условие для прерывания всех циклов - чтобы быстро выйти из функции
        If $GetPath <> 0 Then ExitLoop ; Прерываю циклы всех подфункций
        $Get = FileFindNextFile($File)
        If @error Then ExitLoop
        $String = $Path & "\" & $Get ; Формирую новый путь
        ProgressSet($Progress, $Path & @CR & $Get)
        $Progress = $Progress + 0.1
        If $Progress >= 100 Then $Progress = 0.1
        If Not StringInStr(FileGetAttrib($String), "D") Then ;Если не является папкой тогда:
            If $Get = $FileName Then
                $GetPath = $Path
                ExitLoop
            EndIf
        Else
            _FindFile($String, $FileName) ; Запуск подфункции для поиска в подпапке
        EndIf
    WEnd
    FileClose($File) ;Завершение инициализации
    Return $GetPath
EndFunc

Func SearchButton()
    If Not FileExists(GUICtrlRead($PathInput)) Then
        _MsgBox(16, "Error", "You must type an existing path", $Gui)
    ElseIf StringRight(GUICtrlRead($PathInput), 1) = "\" Then
        _MsgBox(48, "Attention!", "The path must not have a slash (\) at the end of it.", $Gui)
    ElseIf GUICtrlRead($FileNameInput) = "" Then
        _MsgBox(16, "Error", "You must type a file name", $Gui)
    ElseIf Not _IsFileName(GUICtrlRead($FileNameInput)) Then
        _MsgBox(16, 'Error', 'The file name include an invalid characters' & @CR & '< > | ? : * / \ "', $Gui)
    Else
        $PathForSearch = GUICtrlRead($PathInput)
        $FileToFind = GUICtrlRead($FileNameInput)
        GUISetState(@SW_HIDE, $Gui)
        ProgressOn("Please wait...", "Search is in progress...", $PathForSearch, -1, -1, 16)
        $SearchResults = _FindFile($PathForSearch, $FileToFind)
        ProgressOff()
        If Not $SearchResults = 0 Then
            MsgBox(262144+64, "Done!", "File <" & $FileToFind & "> was found in this path <" & $SearchResults & ">.")
        Else
            MsgBox(262144+48, "Attention!", "File <" & $FileToFind & "> was not found on <" & $PathForSearch & "> and it subfolders." & @CR & @CR & "OK ---> EXIT")
        EndIf
        GUISetState(@SW_SHOW, $Gui)
    EndIf
EndFunc

Func _IsFileName($Test)
    If StringRegExp($Test, '[<>|?:"*/\\]') <> 0 Then
        Return False
    Else
        Return True
    EndIf
EndFunc

Func _MsgBox ($MsgBoxType, $MsgBoxTitle, $MsgBoxText, $mainGUI=0)
    $ret = DllCall ("user32.dll", "int", "MessageBox", _
            "hwnd", $mainGUI, _
            "str", $MsgBoxText , _
            "str", $MsgBoxTitle, _
            "int", $MsgBoxType)
    Return $ret [0]
EndFunc

Func ExitScript()
    Exit
EndFunc
 
Автор
T

TERMINAL

Новичок
Сообщения
18
Репутация
1
К примеру - нужно найти на всех носителях файлы типа *.txt...
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8,671
Репутация
2,481
Кажется я писал этот скрипт :smile:

С небольшой(?) коррекцией, он теперь поддерживает нечто вроде класса - [:ALL:]...

Код:
Opt("GuiOnEventMode", 1)

Global $Progress = 0.1, $GetPath = 0
$sPathForSearch = @HomeDrive
$FileToFind = "test.au3"

$hGUI = GUICreate("File Finder", 300, 170, -1, -1, -1, 0x00000088)
GUISetOnEvent(-3, "_ExitScript")

GUICtrlCreateLabel("Path to search on:", 20, 30)
$sPathInput = GUICtrlCreateInput($sPathForSearch, 20, 50, 270)

GUICtrlCreateLabel("File to find:", 20, 90)
$sFileNameInput = GUICtrlCreateInput($FileToFind, 20, 110, 270)

$SearchButton = GUICtrlCreateButton("Search", 70, 140, 60, 20)
GUICtrlSetOnEvent(-1, "_SearchButton")
$CancelButton = GUICtrlCreateButton("Cancel", 180, 140, 60, 20)
GUICtrlSetOnEvent(-1, "_ExitScript")

GUISetState()

While 1
	Sleep(100)
WEnd

Func _FindFile($sPath, $sFileName)
	$ModPath = $sPath & "\*" ; Формирую строку поиска (толко для инициализации)
	$File = FileFindFirstFile($ModPath) ; Инициализация поиска
	
	While 1
		; Условие для прерывания всех циклов - чтобы быстро выйти из функции
		If $GetPath <> 0 Then ExitLoop ; Прерываю циклы всех подфункций
		$Get = FileFindNextFile($File)
		If @error Then ExitLoop
		
		$String = $sPath & "\" & $Get ; Формирую новый путь
		ProgressSet($Progress, $sPath & @CR & $Get)
		$Progress = $Progress + 0.1
		If $Progress >= 100 Then $Progress = 0.1
		
		If Not StringInStr(FileGetAttrib($String), "D") Then ;Если не является папкой тогда:
			If $Get = $sFileName Then
				$GetPath = $sPath
				ExitLoop
			EndIf
		Else
			_FindFile($String, $sFileName) ; Запуск подфункции для поиска в подпапке
		EndIf
	WEnd
	
	FileClose($File) ;Завершение инициализации
	Return $GetPath
EndFunc

Func _SearchButton()
	Local $sSearchResults = 0
	Local $sSearchPath = StringRegExpReplace(GUICtrlRead($sPathInput), "\\+$", "")
	Local $sFileName = GUICtrlRead($sFileNameInput)
	
	If $sSearchPath <> "[:ALL:]" Then
		If Not FileExists($sSearchPath) Then
			Return MsgBox(16, "Error", "You must type an existing path", 0, $hGUI)
		ElseIf $sFileName = "" Then
			Return MsgBox(16, "Error", "You must type a file name", 0, $hGUI)
		ElseIf Not _FileIsFileName($sFileName) Then
			Return MsgBox(16, "Error", "The file name include an invalid characters" & @CRLF & '< > | ? : * / \ "', 0, $hGUI)
		EndIf
	EndIf
	
	GUISetState(@SW_HIDE, $hGUI)
	
	ProgressOn("Please wait...", "Search is in progress...", $sSearchPath, -1, -1, 16)
	
	If $sSearchPath = "[:ALL:]" Then
		Local $aDrives = DriveGetDrive("FIXED")
		
		For $i = 1 To $aDrives[0]
			$sSearchResults = _FindFile($aDrives[$i], $sFileName)
		Next
	Else
		$sSearchResults = _FindFile($sSearchPath, $sFileName)
	EndIf
	
	ProgressOff()
	
	If $sSearchResults <> 0 Then
		MsgBox(262144 + 64, "Done!", "File <" & $sFileName & "> was found in this path <" & $sSearchResults & ">.", 0, $hGUI)
	Else
		MsgBox(262144 + 48, "Attention!", _
			"File <" & $sFileName & "> was not found on <" & $sSearchPath & "> and it subfolders." & @CRLF & @CRLF & _
			"OK ---> EXIT", 0, $hGUI)
	EndIf
	
	GUISetState(@SW_SHOW, $hGUI)
EndFunc

Func _FileIsFileName($sTest)
	Return (StringRegExp($sTest, '[<>|?:"*/\\]') = 0)
EndFunc

Func _ExitScript()
	Exit
EndFunc
 

SECTOR

Продвинутый
Сообщения
399
Репутация
59
CreatoR у меня на твоём скрипте выдаёт:

Код:
C:\Documents and Settings\1-Shot and Gone\??? ?????????\AutoIt Temp\????? ?????\44.au3 (90) : ==> Incorrect number of parameters in function call.: 
MsgBox(262144 + 48, "Attention!", "File <" & $sFileName & "> was not found on <" & $sSearchPath & "> and it subfolders." & @CRLF & @CRLF & "OK ---> EXIT", 0, $hGUI) 
^ ERROR
:(

Если чё то у меня v3.2.8.1
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8,671
Репутация
2,481
Re: Cкрипт для поиска файла на разных носителях [?]
Тогда добавь функцию _MsgBox из первого скрипта, и замени «MsgBox» на «_MsgBox», и «, 0, $hGUI)» на «, $hGUI)».
 
Автор
T

TERMINAL

Новичок
Сообщения
18
Репутация
1
Из-за того что всё красиво НЕКОПИРУЕТСЯ....выходят такие ошибки !

Код:
>"C:\Program Files\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.exe" /run /prod /ErrorStdOut /in "C:\test.au3" /autoit3dir "C:\Program Files\AutoIt3" /UserParams    
+> Starting AutoIt3Wrapper v.1.7.3
>Running AU3Check (1.54.3.0)  params:  from:C:\Program Files\AutoIt3
C:\test.au3(50,73) : ERROR: MsgBox() [built-in] called with wrong number of args.
			Return MsgBox(16, "Error", "You must type an existing path", 0, $hGUI)
			~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\test.au3(52,68) : ERROR: MsgBox() [built-in] called with wrong number of args.
			Return MsgBox(16, "Error", "You must type a file name", 0, $hGUI)
			~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\test.au3(54,116) : ERROR: MsgBox() [built-in] called with wrong number of args.
			Return MsgBox(16, "Error", "The file name include an invalid characters" & @CRLF & '< > | ? : * / \ "', 0, $hGUI)
			~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\test.au3(69,119) : ERROR: MsgBox() [built-in] called with wrong number of args.
		MsgBox(262144 + 64, "Done!", "File <" & $sFileName & "> was found in this path <" & $sSearchResults & ">.", 0, $hGUI)
		~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\test.au3(71,166) : ERROR: MsgBox() [built-in] called with wrong number of args.
		MsgBox(262144 + 48, "Attention!", "File <" & $sFileName & "> was not found on <" & $sSearchPath & "> and it subfolders." & @CRLF & @CRLF & "OK ---> EXIT", 0, $hGUI)
		~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\test.au3 - 5 error(s), 0 warning(s)
!>AU3Check ended.rc:2
>Running:(3.2.0.1):C:\Program Files\AutoIt3\autoit3.exe "C:\test.au3"    
C:\test.au3 (71) : ==> Incorrect number of parameters in function call.: 
MsgBox(262144 + 48, "Attention!", "File <" & $sFileName & "> was not found on <" & $sSearchPath & "> and it subfolders." & @CRLF & @CRLF & "OK ---> EXIT", 0, $hGUI) 
^ ERROR
 
Автор
T

TERMINAL

Новичок
Сообщения
18
Репутация
1
Исправил-подправил....РАБОТАЕТ но не так как хотел-не ищет все *.txt
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8,671
Репутация
2,481
Re: Cкрипт для поиска файла на разных носителях [?]
Из-за того что всё красиво НЕКОПИРУЕТСЯ....выходят такие ошибки !
Это не из за этого, в 3.2.8.1 параметр hWnd не поддерживался.
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8,671
Репутация
2,481
[?]
РАБОТАЕТ но не так как хотел-не ищет все *.txt
А кто сказал что оно поддерживает шаблоны? :smile:
И в первом сообщении ничего не сказано о поиске файлов.
 
Автор
T

TERMINAL

Новичок
Сообщения
18
Репутация
1
Я ненашёл где редактировать и поэтому ниже добавил объяснение... :IL_AutoIt_1:
 

Yashied

Модератор
Команда форума
Глобальный модератор
Сообщения
5,379
Репутация
2,724
Вот написал.

Код:
#Include <File.au3>

;$Drive = DriveGetDrive('ALL')
;If IsArray($Drive) Then
;    For $i = 1 To $Drive[0]
;        _FindFiles($Drive[$i], '*.txt')
;    Next
;EndIf

_FindFiles('C:', '*.txt')

Func _FindFiles($sRoot, $sFile)

    Local $FileList

    $FileList = _FileListToArray($sRoot, $sFile, 1)
    If Not @error Then
        For $i = 1 To $FileList[0]
            ConsoleWrite($sRoot & '\' & $FileList[$i] & @CR)
        Next
    EndIf
    $FileList = _FileListToArray($sRoot, '*', 2)
    If Not @error Then
        For $i = 1 To $FileList[0]
            _FindFiles($sRoot & '\' & $FileList[$i], $sFile)
        Next
    EndIf
EndFunc   ;==>_FindFiles
 

SECTOR

Продвинутый
Сообщения
399
Репутация
59
Скачал v3.3.0.0, всё работает спасибо!
 
Верх