需要帮助创建一个批处理文件,该文件将计算给定文件路径的 md5 校验和并将其输出到 txt 文档

问题描述 投票:0回答:1

我已经获得了使用文件路径处理一个文件并将结果输出到 txt 文档的基本命令。

理想情况下,我想创建一个循环来计算名为“filepathlist.txt”的 txt 文档中列出的每个文件/文件路径的 MD5 校验和

我对 Windows 命令实用程序不太熟悉,不足以让循环工作。

这就是我所拥有的

certutil - hashfile C:\pathtofile\file.xml MD5 >> md5checksums.txt

哪个输出

MD5 hash of C:\pathofile\file.xml:
8c2ad3e4ddd931a456ff1c45c3d294ad2

如前所述,我有一个 txt 文档,其中列出了我需要校验和的所有文件的文件路径。有没有办法循环这个命令,以便它运行所有文件,然后在同一行输出路径和哈希值?

我希望输出看起来像这样

C:\pathoffile\file.xml 8c2ad3e4ddd931a456ff1c45c3d294ad2

任何帮助将不胜感激。谢谢!

windows batch-file cmd
1个回答
-1
投票

我无法让 certutil 仅输出 md5 哈希值。哈希值将写入

md5checksums.txt
文件的第二行。因此,需要一个小辅助循环来从文件中获取第二行。也许有人知道如何解决这个问题。无法通过
certutil -?
找到任何相关内容,但也许可以更深入地了解一下。


将文件作为列表放入这样的文件中。绝对或相对路径。引号是可选的,稍后将在脚本中删除它们。如果您可以确保所有路径都带或不带引号,您可以这样做并相应地更改批处理脚本。

yourFileList.txt

C:\absolute\path\with whitespace\testFile1.txt
testFile2.txt
"testFile3.txt"
test File4.txt
"C:\some\other\path\testFile5.txt"

按如下方式更改批处理文件:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

REM absolute or relative paths to the input and output files
SET "inputFileList=C:\path\with whitespace\yourFileList.txt"
SET "md5File=md5checksums.txt"

for /f "usebackq tokens=*" %%a in ("%inputFileList%") do (
    SET "fileToBeChecked=%%a"
    
    REM The following will remove " in the file from the list. 
    REM Thus making sure that the strings are uniform
    REM You can remove this line if all paths in the list are without quotation marks
    SET fileToBeChecked=!fileToBeChecked:"=!
    
    IF EXIST "!fileToBeChecked!" (
        certutil -hashfile "!fileToBeChecked!" MD5>%md5File%

        REM Read the second line from the generated File. That is where the hash is placed.
        FOR /f "tokens=1*delims=:" %%G IN ('findstr /n "^" %md5File%') DO IF %%G EQU 2 SET md5Result=%%H
        
        ECHO !fileToBeChecked! !md5Result!
    ) ELSE (
        ECHO !fileToBeChecked! File not found.
    )
)

REM If you don't need the help file md5checksums.txt you can do so
DEL %md5File%

PAUSE

结果:

C:\absolute\path\testFile1.txt 81dc9bdb52d04dc20036dbd8313ed055
testFiel2.txt 81b073de9370ea873f548e31b8adc081

注1: 如果文件为空,将会出现错误消息。您应该检查一下是否可能出现这种情况。
注 2: 可以将所有 ECHO 行放入第二个结果文件中,然后

TYPE
将文件输出到末尾

© www.soinside.com 2019 - 2024. All rights reserved.