比较目录和子目录,并根据MD5哈希替换文件

时间:2017-01-26 15:15:59

标签: powershell md5

有一个基于MD5哈希进行比较的比较脚本。注意到它做的很奇怪。

 $Source=  "D:\Folder1"
$Destination = "D:\folder2"

get-childitem $Source -Recurse | foreach {
 #Calculate hash using Algorithm MD5 reference http://www.tomsitpro.com/articles/powershell-file-hash-check,2-880.html
 Write-Host "Copying $($_.fullname) to $Destination" -ForegroundColor Yellow
 $OriginalHash = Get-FileHash -Path $_.FullName -Algorithm MD5

 #Now copy what's different
 $replacedfile = $_ | Copy-Item -Destination $Destination -Force -PassThru

 #Check the hash sum of the file copied
 $copyHash = Get-FileHash -Path $replacedfile.FullName -Algorithm MD5

 #compare them up
 if ($OriginalHash.hash -ne $copyHash.hash) {
    Write-Warning "$($_.Fullname) and $($replacedfile.fullname) Files don't match!" 
 }
 else {
    Write-Host "$($_.Fullname) and $($replacedfile.fullname) Files Match" -ForegroundColor Green
 }
} #Win!

该脚本工作正常,直到找到子文件夹中的差异。然后由于某种原因,我似乎无法找到,它将不同的项目复制到顶层和子层......我真的很笨,我看不出问题,需要第二对眼睛。

实施例

File Test.Txt is in Source\SubFolder

脚本运行并将Test.Txt放入Destination \ Subfolder AND Destination .....

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

$replacedfile = $_ |是错误,这里$ _只包含没有subdir的名称,并被复制到$ Destination。

替换行:

$replacedfile = $_ | Copy-Item -Destination $Destination -Force -PassThru

使用:

$replacedfile = $_.Fullname -replace [RegEx]::escape($Source),$Destination

这取代了不同的基础部分,使得固有源子目录完整无缺。 [RegEx] :: escape($ Source)是必需的,因为源字符串包含
反斜杠,它将被替换函数解释为转义字符。

编辑完整的脚本以避免含糊不清:

$Source=  "D:\Folder1"
$Destination = "D:\folder2"

get-childitem $Source -Recurse | foreach {
    #Calculate hash using Algorithm MD5 reference http://www.tomsitpro.com/articles/powershell-file-hash-check,2-880.html
    $SrcFile = $_.FullName
    $SrcHash = Get-FileHash -Path $SrcFile -Algorithm MD5

    $DestFile = $_.Fullname -replace [RegEx]::escape($Source),$Destination
    Write-Host "Copying $SrcFile to $DestFile" -ForegroundColor Yellow

    if (Test-Path $DestFile) {
        #Check the hash sum of the file copied
        $DestHash = Get-FileHash -Path $DestFile -Algorithm MD5

        #compare them up
        if ($SrcHash.hash -ne $DestHash.hash) {
            Write-Warning "$SrcFile and $DestFile Files don't match!" 
            Copy-Item $SrcFile -Destination $DestFile -Force
        } else {
            Write-Host "$SrcFile and $DestFile Files Match" -ForegroundColor Green
        }
    } else {
        Copy-Item $SrcFile -Destination $DestFile -Force
    }
}