我有一個包含檔案的目錄和一個 ControlFile.txt,其中包含各種檔案的 SHA256 總和串列。我試圖想出一個批處理程序來遍歷目錄中的檔案,計算每個檔案的 SHA256 值,然后比較計算出的 SHA256 是否存在于 ControlFile.txt 中并相應地進行分支。
我試圖用以下內容制作一個作業腳本,但我相信我缺少一些關鍵元素:
for /R . %%f in (*.*) do (
find /c "(certutil -hashfile "%%f" SHA256 | findstr /V "hash")" ControlFile.txt > NUL
if %errorlevel% equ 1 goto notfound
echo "%%f" found
goto done
:notfound
echo "%%f" notfound
goto done
:done)
我相信我可能需要為給定的 SHA256 值設定一個變數,并在回圈中使用它來產生我想要實作的比較函式,但是我對批處理檔案和 cmd 的了解是有限的。任何代碼建議將不勝感激。
uj5u.com熱心網友回復:
@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q74148620.txt"
FOR /f "delims=" %%b IN ('dir /s /b /a-d "u:\j*" ') DO (
FOR /f %%y IN ('certutil -hashfile "%%b" SHA256 ^| find /V ":"') do (
findstr /x "%%y" "%filename1%" > NUL
IF ERRORLEVEL 1 (
ECHO "%%b" NOT found
) ELSE (
ECHO "%%b" found
)
)
)
GOTO :EOF
我使用了j*用于測驗的檔案掩碼 - 更改以適應。
只需certutil依次在每個檔案上運行例程,過濾掉任何包含 的行:,留下 SHA256 資料。將該值定位為/x與 SHA256 值檔案中的一行精確匹配的值。如果找到匹配項,errorlevel則設定為0,否則設定為非0,然后打開errorlevel。
===不包含子目錄的小修改===
@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q74148620.txt"
PUSHD "%sourcedir%"
FOR /f "delims=" %%b IN ('dir /b /a-d') DO (
FOR /f %%y IN ('certutil -hashfile "%%b" SHA256 ^| find /V ":"') do (
findstr /x "%%y" "%filename1%" > NUL
IF ERRORLEVEL 1 (
ECHO "%%b" NOT found
) ELSE (
ECHO "%%b" found
)
)
)
POPD
GOTO :EOF
這些dir選項/b僅顯示名稱(不顯示大小、日期等),/s將掃描子目錄并生成帶有完整路徑的檔案名,并/a-d抑制目錄名稱。u:\j*是串列的開始位置;drive u:,所有開始的檔案j(用于測驗)。
該pushd命令使指定目錄成為當前目錄,因此修改后的dir命令將僅掃描該目錄的所有檔案名,但不掃描目錄名(因為沒有提供起始目錄和檔案掩碼)。
該popd命令回傳到原始目錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520292.html
