比较文件名而不是哈希值的对象过滤器

时间:2017-07-25 08:13:14

标签: powershell hash

我使用的脚本将文件从本地存储移动到我们的中央存储。

将它放在中央存储设备上后,我要在本地和中央进行比较,以确保所有内容都正确放置在那里。 每当出现问题时,我都会得到文件的哈希值而不是文件本身。 显然,对于我的最终用户来说,如果文件本身出现错误的地方而不是哈希值,那将会更有用。

Compare-Object -ReferenceObject (dir $nas_smb_share -Recurse | Where-object{(!$_.psiscontainer) } | get-hash)  -differenceObject (dir $cs_dest -Recurse  | Where-object{(!$_.psiscontainer) -AND ($_.LastWriteTime -gt (Get-Date).AddHours(-1))} | get-hash)  -Property Name -PassThru |
%{if ($_.SideIndicator -eq "=>" ){$result = ("$($_.InputObject)")}}

这里我使用compare-object的结果,使用它来获取文件,但我没有设法获得实际文件而不是哈希值。 可能与-Property Name Passtru有关?

if ([string]::IsNullOrEmpty($result)){$res = "Transfer succeeded without problems"}
else {
$hash_error = 1
$res = ("transfer failed on following file(s): "+ (dir $cs_dest -Recurse  | 
Where-Object {(!$_.psiscontainer)} | get-hash | ? {$_.hashstring -match 
$result}) )
}

感谢allready的任何输入。

注意:正在移动的文件是取证图像,这些图像被分成大约1,5Gb的部分。因此,除非您拥有所有部件,否则数据无法以任何方式读取。

1 个答案:

答案 0 :(得分:0)

我可能误读了你在这里问的内容 - 但我有一些代码用于在服务器上复制文件并确认它已成功复制,看起来它至少应该适合你的用例。

$TimeSince = (Get-Date).AddHours(-1)
Get-ChildItem "LocalDrive" | ? {$_.LastWriteTime -gt $TimeSince} | % {
    #Details of both local and remote files, this is run from local storage.
    $LocalFile = $_.FullName
    $RemoteFile = Join-Path "RemoteDrive" $_.Name

    #Copy file to remote directory if it doesn't exist - sounds like you can remove this part.
    if (!(Test-Path $RemoteFile)){
        Write-Host "Copying '$($LocalFile)' -> '$($RemoteFile)'" -Fore Yellow
        Copy-Item $LocalFile $RemoteFile
    }

    #Calculate both hashes and do a normal compare inside an IF, output can easily be changed.
    $LocalHash = Get-FileHash $LocalFile -Algorithm MD5
    $RemoteHash = Get-FileHash $RemoteFile -Algorithm MD5

    if ($LocalHash.Hash -ne $RemoteHash.Hash){
        Write-Host "Mismatch with '$($_.Name)'" -Fore Red
    }
}

我的原始脚本有更多的错误处理,但它都非常通用。

就像一个注释 - 如果你正在使用比较对象,它返回的'结果'仅限于它所比较的​​ - 你需要保留一个单独的'显示'值跟踪,如果你想使用替代的