#include <FileConstants.au3>
#include <Array.au3>

Global $sourceFolder = "G:\test_bak"
Global $destinationFolder = "G:\select"
Global $listFilePath = "G:\list.txt"
Global $logFilePath = "G:\search_log.txt"

; 读取清单文件
Global $listArray = FileReadToArray($listFilePath)

If @error Then
    MsgBox($MB_ICONERROR, "Error", "Failed to read list file!")
    Exit
EndIf

; 打开日志文件
Global $logFile = FileOpen($logFilePath, $FO_APPEND)

If $logFile = -1 Then
    MsgBox($MB_ICONERROR, "Error", "Failed to open log file!")
    Exit
EndIf

; 遍历清单中的每一项
For $item In $listArray
    ; 搜索文件名包含清单中任何一项的文件
    SearchFiles($sourceFolder, $item)
Next

FileClose($logFile)
MsgBox(64, "Info", "Search completed! Please check the log file for details.")

; 搜索文件名包含指定项的函数
Func SearchFiles($folderPath, $itemName)
    Local $search = FileFindFirstFile($folderPath & "\*.*")

    If $search = -1 Then
        FileWriteLine($logFile, "File not found for item: " & $itemName)
    Else
        While 1
            Local $fileName = FileFindNextFile($search)
            If @error Then ExitLoop

            ; 如果文件名包含指定项,则复制到目标文件夹
            If StringInStr($fileName, $itemName) Then
                If Not FileCopy($folderPath & "\" & $fileName, $destinationFolder & "\" & $fileName, $FC_OVERWRITE) Then
                    MsgBox($MB_ICONERROR, "Error", "Failed to copy file: " & $fileName)
                EndIf
            EndIf

            ; 如果是文件夹,则递归搜索其中的文件
            If StringInStr(FileGetAttrib($folderPath & "\" & $fileName), "D") Then
                SearchFiles($folderPath & "\" & $fileName, $itemName)
            EndIf
        WEnd

        FileClose($search)
    EndIf
EndFunc