如何计算批处理脚本中特定文件的哈希值



我是批处理脚本的新手,在尝试计算特定文件的哈希值时遇到几行问题。

我正在编写一个脚本来检查我将从一个地方发送到另一个地方的文件。为了检查文件是否相同,我需要计算文件在发送之前和发送后的哈希值,以比较哈希值以确保它相同。下面是我编写的代码,用于计算和比较文件的哈希值。

set original=CertUtil -hashfile \172.168.101.187smb1GBTESTFILE.TXT MD5
set received=CertUtil -hashfile \172.168.101.188smb1GBTESTFILE.TXT MD5
if original==received(
echo no file lost
) else (
echo file lost
)

应该期待"没有文件丢失",但是,我收到"命令的语法不正确"。

不能使用 set 将命令的输出存储到变量中,需要改用 for /F 循环。另请注意,CertUtil返回的不仅仅是哈希值:

rem /* At first, clear variable that is going to receive the hash value;
rem    then use `for /F` to capture the output of `CertUtil`, skipping the first line,
rem    which merely contains the text `MD5 hash of file`, the file name/path and `:`;
rem    the `if defined` line ensures that only the second line of the output is captured,
rem    so the summary line `CertUtil: -hashfile command completed successfully.` is dismissed;
rem    the `2^> nul` part avoids error messages by `CertUtil`: */
set "ORIGINAL=" & for /F "skip=1 delims=" %%H in ('
    2^> nul CertUtil -hashfile "\172.168.101.187smb1GBTESTFILE.TXT" MD5
') do if not defined ORIGINAL set "ORIGINAL=%%H"
rem // Same procedure for the second hash value:
set "RECEIVED=" & for /F "skip=1 delims=" %%H in ('
    2^> nul CertUtil -hashfile "\172.168.101.188smb1GBTESTFILE.TXT" MD5
') do if not defined RECEIVED set "RECEIVED=%%H"
rem /* Conditional actions; regard that you need surrounding `%%` to read variables;
rem    also note the spaces in front of `(`!: */
if "%ORIGINAL%%RECEIVED%"=="" (
    >&2 echo ERROR: no hashes available!
) else (
    if "%ORIGINAL%"=="%RECEIVED%" (
        echo INFO:  hashes match.
    ) else (
        if "%ORIGINAL%%RECEIVED%"=="%RECEIVED%%ORIGINAL%" (
            >&2 echo ERROR: one hash is missing!
        ) else (
            >&2 echo ERROR: hashes differ!
        )
    )
)

最新更新