使用 Windows 批次腳本從文件清單複製具有符合檔案名稱的網路文件

使用 Windows 批次腳本從文件清單複製具有符合檔案名稱的網路文件

我有 2 個文件,其中 1 個包含某些關鍵字,另一個包含路徑列表。我想從第一個檔案清單中搜尋關鍵字到檔案路徑清單中,如果找到,則將檔案從指定的檔案路徑複製到特定的目標資料夾。

第一個文件內容

Keyword1
Keyword2
Keyword3
Keyword4

第二個文件內容

\\server\path...\Keyword1.txt
\\server\path...\Keyword1_0_1.txt
\\server\path...\Keyword2_0_1.txt
\\server\path...\Keyword2_1_9.txt
\\server\path...\Keyword3_1_0_1.txt

為此我必須編寫 Windows 批次腳本。

================================================== = =========

抱歉@pimp-juice-it,我不知道如何貼上螢幕截圖。因此複製貼上下面的輸出 -

d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\33.txt" %G IN (55*) DO ECHO "55" d:\Temp_Script\Script>CALL :FileExist "55" "D: \Temp_Script\Source\44.txt" d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\44.txt" %G IN (55*) DO ECHO "55" d:\Temp_Script\Script> CALL :FileExist "55" "D:\Temp_Script\Source\55.txt" d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\55.txt" %G IN (55*) DO ECHO " 55" d:\Temp_Script\Script>CALL :FileExist "55" "D:\Temp_Script\Source\55 - 複製(2).txt" d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\ 55 - 複製(2).txt" %G IN (55*) DO ECHO "55" d:\Temp_Script\Script>CALL :FileExist "55" "D:\Temp_Script\Source\55 - Copy.txt"

正如您可以看到 UNC 中存在關鍵字“55”,但條件在 FOR 循環中仍然未驗證為 True,並且將直接轉到下一個 UNC。下面是程式碼 -

:FileExist FOR /R "%~2" %%G IN (%~1*) DO ECHO "%~1"

答案1

您可以循環遍歷“關鍵字”列表一次,並使用迭代的關鍵字值以及一些封閉的通配符作為搜尋字串IE *<Keyword>*。您可以從檔案清單中遍歷每個 UNC 路徑值的目錄樹,並僅對那些與搜尋字串「keywords」相符的目錄樹執行複製作業。

本質上雖然...

  • 首先對於 /f循環將逐一讀取字串檔案清單的每一行,每一行的值將是一個迭代值,該值在第一個參數處傳遞給 稱呼命令。
  • 第二對於 /f循環將逐行讀取UNC路徑檔案清單的每一行並傳遞它和第一個傳遞的第一個參數值對於 /f循環作為兩個參數及其 稱呼命令。
  • 最後對於/r循環將遞歸搜尋迭代的 UNC 路徑,並將迭代的字串值作為傳遞的單獨參數,然後複製所有符合的檔案。

批次腳本

@ECHO ON

SET "strList=\\server\Folder\Path\SearchStrings.txt"
SET "pathList=\\server\Folder\Path\UNCPaths.txt"
SET "targetPath=\\server\target\folder\path"

FOR /F "USEBACKQ TOKENS=*" %%S IN ("%strList%") DO CALL :Paths "%%~S"
PAUSE
EXIT

:Paths
FOR /F "USEBACKQ TOKENS=*" %%P IN ("%pathList%") DO CALL :FileExist "%~1" "%%~P"
GOTO :EOF

:FileExist
FOR /R "%~2" %%C IN (*%~1*) DO XCOPY /F /Y "%%~C" "%targetPath%\"
GOTO :EOF

更多資源

  • 對於/F

  • 稱呼

    CALL 指令將會將控制權傳遞給指定標籤以及任何指定參數之後的語句。若要退出子例程,請指定GOTO:eof這會將控制權轉移到目前子例程的末端。

  • 對於/R

    FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
    
        Walks the directory tree rooted at [drive:]path, executing the FOR
        statement in each directory of the tree.  If no directory
        specification is specified after /R then the current directory is
        assumed.  If set is just a single period (.) character then it
        will just enumerate the directory tree.
    

相關內容