powershell md5比较慢

时间:2016-07-13 11:11:45

标签: powershell powershell-v2.0

我正在尝试使用md5哈希与powershell 2.0比较几个文件。 代码有效,问题是它会变慢。 第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
        }
    }
}

2 个答案:

答案 0 :(得分:0)

比较文件,例如4096字节。

  1. 例如,使用[IO.FileStream] class从两个文件中读取4096个字节。
  2. 计算并比较md5
  3. 循环直到文件结束
  4. 我建议比较前4096个字节,然后是最后4096个字节,然后以线性方式进行 这就是我在类似的实用程序中所做的。

    通过尝试各种值来确定数字。

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

答案 1 :(得分:0)

我采用了另一种方法,因为问题不是MD5的时间。 我将2个目录内容发送到一个数组中,然后使用这些数组进行所有操作。 450个文件的时间从大约一个小时到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
            }
        } 
    }