1

I write a Function in PowerShell script to compare the hash between two files. This is my code:

Function Compare-Hash {
    param (
        $FILE_1,
        $FILE_2
    )

    $HASH_1 = Get-FileHash $FILE_1 -Algorithm SHA256 | Format-List Hash
    $HASH_2 = Get-FileHash $FILE_2 -Algorithm SHA256 | Format-List Hash
    $HASH_MATCHED = @(Compare-Object $HASH_1 $HASH_2).Lenght -eq 0

    If ($HASH_MATCHED) {
        Write-Host -ForegroundColor Green Hash matched!
    }
    else {
        Write-Host -ForegroundColor Red Hash not matched!
    }
}

I tried that Function with the same file:

Compare-Hash test.txt test.txt

But it returned:

Hash not matched!

I also try with

If ($HASH_1 -eq $HASH_2)

But it still returns false.
I am sticking with this problem and I don't know why this happened. I also print $HASH_1 and $HASH_2 to check it manually but those are the same!
Could you show me what my problem is and how to fix it? Thank you very much.

caionam
  • 15
  • 3
  • 1
    change "lenght" to "length", this might cause the issue – Odysseas Tsimpikakis Mar 14 '23 at 15:14
  • 1
    `Format-*` cmdlets emit output objects whose sole purpose is to provide _formatting instructions_ to PowerShell's for-display output-formatting system. In short: only ever use `Format-*` cmdlets to format data _for display_, never for subsequent _programmatic processing_ - see [this answer](https://stackoverflow.com/a/55174715/45375) for more information. – mklement0 Mar 14 '23 at 15:59

1 Answers1

4

You're not comparing the hashes, you're comparing two sets of formatting data.

Replace Format-List with ForEach-Object to grab just the value of the Hash property:

$HASH_1 = Get-FileHash $FILE_1 -Algorithm SHA256 | ForEach-Object Hash
$HASH_2 = Get-FileHash $FILE_2 -Algorithm SHA256 | ForEach-Object Hash
$HASH_MATCHED = @(Compare-Object $HASH_1 $HASH_2).Length -eq 0
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206