复制后如何对源和目标进行MD5校验

How to perform an MD5 verification on source and destination after copying

我们有大约 4gb 的有效负载,我们需要将其自动复制到多个地理位置,有时程序集(dll 文件)会通过网络损坏。我在 powershell 中使用 get-hash 函数,我的示例代码片段如下所示

# PowerShell Invoke-Command source Machine has check
Clear-Host
Invoke-Command -ScriptBlock {dir C:\swtools-Zip -Recurse | Where-Object {!$_.psiscontainer } | get-hash | Out-File c:\temp\source.md5.txt}

# PowerShell Invoke-Command on Remote Computer to check filehash at Dest
Clear-Host
Invoke-Command -Computer Remote_Host -ScriptBlock {dir e:\downloads-zip -Recurse | Where-Object {!$_.psiscontainer } | get-hash } | Out-File c:\temp\dest.md5.txt

# PowerShell compare to check if the md5 hashes are equal at source and dest

Compare-Object $(Get-Content c:\temp\source.md5.txt) $(Get-Content c:\temp\dest.md5.txt) -includeequal

这并没有解决问题,因为 get-hash 的输出包含添加到文件名的文件路径,所以我无法真正对源文件名和哈希以及文件名和哈希进行 1:1 比较来自目标,因为输出包含不同的完整文件路径

那么确保从源复制到目标的所有程序集的 md5 校验和匹配的最佳方法是什么?

注意:我不打算创建额外的文件,我只通过正则表达式推送文件名和散列等,时间和内存将是一个问题。

您可以通过管道传输到 Tee-Object 以转储到文件(如果您觉得需要转储到文件),然后到 Select-Object 以将 Path 值修改为排除根路径,并将其捕获到 运行 您的 Compare-Object 反对的变量中。以下将输出您的文件,并捕获哈希输出的修改版本,其中 Path 将排除根路径,并且仅包括子文件夹和文件名。

# PowerShell Invoke-Command source Machine has check
Clear-Host
$LocalRoot = [RegEx]::Escape('C:\swtools-Zip')
$LocalHash = Invoke-Command -ScriptBlock {dir C:\swtools-Zip -Recurse | Where-Object {!$_.psiscontainer } | get-hash} | Tee-Object -File c:\temp\source.md5.txt | Select *,@{l='Path';e={$_.Path -replace $LocalRoot}} -ExcludeProperty Path

# PowerShell Invoke-Command on Remote Computer to check filehash at Dest
Clear-Host
$DestRoot = [RegEx]::Escape('e:\downloads-zip')
$DestHash = Invoke-Command -Computer Remote_Host -ScriptBlock {dir e:\downloads-zip -Recurse | Where-Object {!$_.psiscontainer } | get-hash } | Tee-Object -file c:\temp\dest.md5.txt | Select *,@{l='Path';e={$_.Path -replace $DestRoot}} -ExcludeProperty Path

# PowerShell compare to check if the md5 hashes are equal at source and dest

Compare-Object $LocalHash $DestHash -includeequal