powershell md5 比较慢

powershell md5 compare too slow

我正在尝试使用 powershell 2.0 比较使用 md5 散列的几个文件。 代码有效,问题是它太慢了。 第 3 步需要更长的时间。 大约有 500 个文件可供比较。 你能找到更快的方法吗,比如,不要每次都执行第 3 步?

write-host "1"
    $COMP_ORI=$LOCAL_HOME+"\"+$PROG+"\"+$COMPARE
    $file_ori = Get-ChildItem -Path $COMP_ORI -name
write-host "2"
    $COMP_DEST="\"+$HOSTIP[$i]+"\"+$PROG_PATH
    $file_dest = Get-ChildItem -PATH $COMP_DEST -name
write-host "3"
    for ($i=0; $i -lt $file_ori.Count; $i++) {
write-host "compare md5" $i
    if ( Get-ChildItem -PATH $COMP_DEST -name -Include $file_ori[$i] ) {
        $md5 = New-Object -TypeName system.Security.Cryptography.MD5CryptoServiceProvider
write-host "4"
        $hash_ori = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($COMP_ORI+"\"+$file_ori[$i])))
write-host "5"
        $hash_dest = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($COMP_DEST+"\"+$file_ori[$i])))
write-host "6"
        if ($hash_ori -ne $hash_dest) {
            $out=$file_ori[$i]
            $out=$out+" IS DIFFERENT"
            output message_solo $out
        }
    }
}

比较文件块,例如 4096 字节。

  1. 例如,使用 [IO.FileStream] class 从两个文件中读取 4096 字节。
  2. 计算并比较md5
  3. 循环直到到达文件末尾

我建议比较前 4096 个字节,然后比较最后 4096 个字节,然后以线性方式进行。
这是我在类似实用程序中所做的。

通过尝试各种值微调数字。

不要忘记先比较文件大小:不同大小的文件不需要计算MD5
因为它会有所不同。

我采用了另一种方法,因为问题不是 MD5 时间。 我将 2 个目录内容发送到一个数组中,然后所有操作都是使用这些数组进行的。 450 个文件的时间从大约 1 小时缩短到 10 分钟。

$COMP_CS=$LOCAL_HOME+"\"+$PROG+"\"+$COMPARE
$FILE_CS=@(Get-ChildItem -Path $COMP_CS -name -exclude sqlnet.log)
$COMP_BASE="\"+$HOSTIP[$i]+"\"+$PROG_PATH
$FILE_BASE=@(Get-ChildItem -PATH $COMP_BASE -name -exclude sqlnet.log)
    for ($i=0; $i -lt $FILE_CS.length; $i++) {
        if ($FILE_CS -contains $FILE_BASE[$i]) {
            $md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
            $HASH_CS = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($COMP_CS+"\"+$FILE_CS[$i])))
            $HASH_BASE = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($COMP_BASE+"\"+$FILE_CS[$i])))
            if ($HASH_CS -ne $HASH_BASE) {
                $out=$FILE_CS[$i]
                $out=$out+" IS DIFFERENT"
                output message_solo $out
            }
        } 
    }