【问题标题】:Comparing MD5 hashes of two different directories in Powershell比较 Powershell 中两个不同目录的 MD5 哈希值
【发布时间】:2021-04-05 01:42:54
【问题描述】:

我对 Powershell 很陌生,所以请原谅我缺乏经验或缺乏最佳实践。 我正在编写一个脚本,它将首先以 CSV 格式存储两个不同目录的 MD5 哈希值。然后我想比较这两个文件,如果这两个 CSV 文件有任何更改(即文件的 MD5 哈希不匹配,或者源文件夹的 CSV 文件中的一个文件在目标文件夹的 CSV 文件中不存在),我想生成一个新列表,其中包含不匹配或缺失文件的详细信息。

除此之外,我想知道是否有更快的方法来比较这两个文件,因为我正在处理的文件夹非常大,其中包含大约 12k 个文件。我在想,也许我会尝试保持源 CSV 完整,并在检查和验证时从目标 CSV 中一一删除条目。谁能帮我解决这个问题?

#Getting the MD5 hash of the Installer and storing it a csv format
$SourcePath = Get-ChildItem -Path C:\source -Recurse
$SourcerHash = foreach ($File in $SourcePath) 
{
    Get-FileHash $File.FullName -Algorithm MD5
}
$SourceHash | Export-Csv -Path C:\Users\abcd\Desktop\CSVExports\SourceHash.csv

#Getting the MD5 hash of the destination directory and storing it in a csv format
$DestinationPath = Get-ChildItem -Path C:\destination -Recurse
$DestinationHash = foreach ($File in $DestinationPath) 
{
    Get-FileHash $File.FullName -Algorithm MD5    
}
$DestinationHash | Export-Csv -Path C:\Users\abcd\Desktop\CSVExports\DestinationHash.csv

#Comparing the hashes of Installer and Destination directories
Compare-Object -ReferenceObject (Import-Csv C:\Users\abcd\Desktop\CSVExports\InstallerHash.csv) -DifferenceObject (Import-Csv C:\Users\abcd\Desktop\CSVExports\DestinationHash.csv) -Property Hash | Export-Csv C:\Users\abcd\Desktop\CSVExports\ResultTable

【问题讨论】:

标签: powershell csv hash md5


【解决方案1】:
param(
   $firstDirectoryName = "D:\tmp\001",
   $SecondDirectoryName = "D:\tmp\002"
)
$firstList = Get-ChildItem $firstDirectoryName -File -Recurse | ForEach-Object {
   [PSCustomObject]@{
      relativePath =  $_.FullName.TrimStart($firstDirectoryName)
      hash = (Get-FileHash $_.FullName -Algorithm MD5).Hash
   }
}
$secondList = Get-ChildItem $SecondDirectoryName -File -Recurse | ForEach-Object {
   [PSCustomObject]@{
      relativePath =  $_.FullName.TrimStart($SecondDirectoryName)
      hash = (Get-FileHash $_.FullName -Algorithm MD5).Hash
   }
}

Compare-Object -ReferenceObject  $firstList -DifferenceObject $secondList -Property relativePath, hash


【讨论】:

    【解决方案2】:

    你能多解释一下这个练习的用例吗?我看起来其他一些工具在这方面会比尝试在 PowerShell 中执行此操作更有效,例如适当的文件同步工具。

    不管怎样,既然你问了:

    • 您需要多久检查一次哈希?
    • 也许只检查最近更新的文件,而不是检查所有 12k 文件?
    • Posh v7 支持 foreach 并行,可以加快进程。

    【讨论】:

    • 这是一个安装程序,我需要将源目录的哈希值与目标目录进行比较。 1. 我只需要在安装程序运行后检查一次哈希值 2. 由于它将是全新安装,我必须第一次为所有 12k 文件运行它。
    • 你不能压缩这两个文件夹并比较压缩文件的哈希值吗?
    猜你喜欢
    • 2016-08-20
    • 2019-01-02
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多