I'm very new to Powershell, but am attempting to write a simple function to compare two files using their hashes. I'm getting some unexpected results using the following :
$hash1 = Get-FileHash $source | Select-Object Hash
Write-Host(" hash1 : " + $hash1)
returns : hash1 : @{Hash=93725215281E09E21317EA88E03B246AE13890ED96BB0B842A05A5E4969A4BFA}
$hash2 = Get-FileHash $destination | Select-Object Hash
Write-Host(" hash2 : " + $hash2)
returns : hash2 : @{Hash=93725215281E09E21317EA88E03B246AE13890ED96BB0B842A05A5E4969A4BFA}
$hashdiff = ($hash1 -eq $hash2)
Write-Host(" hashdiff : " + $hashdiff)
returns : hashdiff : False
I'm sure it's an obvious mistake, but can somebody put me out of my misery and help me understand why the equality operator isn't working as expected?
Many thanks in advance
The lines Get-FileHash $source | Select-Object Hash
(same for $destination
) return PSObjects containing a property Hash
.
It's that property you want to compare, so either do
$hashdiff = ($hash1.Hash -eq $hash2.Hash)
Or get the hash string values and compare those:
$hash1 = Get-FileHash $source | Select-Object -ExpandProperty Hash
Write-Host(" hash1 : " + $hash1)
$hash1.gettype().fullname
$hash1
$hash2 = Get-FileHash $destination | Select-Object -ExpandProperty Hash
Write-Host(" hash2 : " + $hash2)
$hashdiff = ($hash1 -eq $hash2)
Write-Host(" hashdiff : " + $hashdiff)
Result:
hash1 : 6A9F599704B0895581ED47805F80137120D14E824DA19A78C2808576A8A0405B hash2 : 6A9F599704B0895581ED47805F80137120D14E824DA19A78C2808576A8A0405B hashdiff : True