2016-07-13 64 views
0

我想比较几个文件使用md5哈希与PowerShell 2.0。代码起作用,问题在于速度慢。 在第3步需要更长的时间。 大约需要比较500个文件。 你能否看到一种让它更快的方法,比如,不要每次都做第3步?powershell MD5比较太慢

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 
     } 
    } 
} 
+0

[codereview.se]是用于改进工作代码的stackexchange站点。你可以尝试在那里发布它,但计算md5sums是一个非常着名的算法,你不可能加快这一部分。 –

+2

但是你可以通过调用一次'Get-ChildItem -PATH $ COMP_DEST [..]'来加速并存储结果,然后使用'-contains'来测试。列出远程文件共享500次不会很快。如果您可以让远程服务器使用PowerShell远程计算来计算dest文件的散列值,那么可以节省通过网络读取文件数据。 – TessellatingHeckler

回答

0

我去了另一种方法,因为问题不是MD5时间。 我将2个目录内容发送到一个数组中,然后使用这些数组完成所有操作。 时间从450小时约1小时到10分钟。

$COMP_CS=$LOCAL_HOME+"\"+$PROG+"\"+$COMPARE 
[email protected](Get-ChildItem -Path $COMP_CS -name -exclude sqlnet.log) 
$COMP_BASE="\\"+$HOSTIP[$i]+"\"+$PROG_PATH 
[email protected](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 
      } 
     } 
    } 
0

将文件以4096字节为单位进行比较。

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

我建议将第一4096个字节文件的末尾,那么最后的4096个字节,然后继续以线性方式。
这就是我在类似的实用程序中所做的。

通过尝试各种值来改变数字。

不要忘了比较文件大小冷杉:不需要计算不同大小的文件的MD5
,因为它会有所不同。