Alex Rivera | Logout

Compare Filehash in Powershell

Asked 2012-07-31T18:03:23.933
17

I'm using PowerShell and I'm trying to figure out how to compare the hashes of multiple files in two different directories. My script downloads files from an FTP site into a directory ($cDlPath) and copies them to another directory ($cDestPath). I'm using the Get-Hash cmdlet to get the file hash, but I can't figure out how to compare the two hashes. I want to be able to identify the altered file(s) by name.

I've been fiddling around with the code below, but it doesn't seem to be what I'm after.

Compare-Object `
-ReferenceObject $(Get-ChildItem $cDestPath -Recurse | Where-Object {!$_.psiscontainer } | Get-Hash -Algorithm $cHashAlg) `
-DifferenceObject $(Get-ChildItem  $cDlPath -Recurse | Where-Object {!$_.psiscontainer } | Get-Hash -Algorithm $cHashAlg)

I'm using the code below and I seem to be a little closer.

Compare-Object $(Get-ChildItem $cDlPath -Recurse $_ | Where-Object { !$_.PsIsContainer } |  
  Select-Object Name, FullName, Length, @{Name=”SHA256 Hash”; Expression={ Get-Hash $_.FullName  
  -Algorithm "SHA256" }}, LastWriteTime) $( Get-ChildItem $cDestPath -Recurse $_ | Where-Object  
  { !$_.PsIsContainer } | Select-Object Name, FullName, Length, @{Name=”SHA256 Hash”; 
  Expression={ Get-Hash $_.FullName -Algorithm "SHA256" }}, LastWriteTime) -property @
  ("Name", “FullName”,”SHA256 Hash”, "Length", "LastWriteTime" ) | Add-Content -Path $cLogFile

It still looks like it isn't completely right though because there are some hashes that are the same and the output to the logfile is ugly. The files should only be in the log file if they have the same hash.

@{Name=nothing.xlsx; FullName=C:\Test\nothing.xlsx; SHA256 Hash=E74424B6324DE014CB0C896DA29D67A2A729E31DF57119E840CA4BD9A9E41754; Length=8891; LastWriteTime=7/31/2012 1:33:11 PM; SideIndicator=<=}
@{Name=test.txt; FullName=
Edit
Report

1 Answer

1

There has to be a prettier solution, but this is what I ended up using.

# Get the file hashes
$hashsourcefile = Get-Hash $file -Algorithm "SHA256"
$hashdestfile = Get-Hash $file2 -Algorithm "SHA256"

# Compare the hashes
Compare-Object -Referenceobject $hashsourcefile -Differenceobject $hashdestfile | % { If ($_.Sideindicator -ne " ==") {$diff+=1} }                  

# The Hashes are different. Note this in the log
if ($diff -ne 0)
{
    Add-Content -Path $cLogFile -Value " Source File Hash: $hashsourcefile does not equal 
    Existing Destination File Hash: $hashdestfile the files are NOT EQUAL."
}
answered 2012-08-20T17:59:54.633

Your Answer