Skip to content

Instantly share code, notes, and snippets.

@chrisbrownie
Last active January 11, 2022 04:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbrownie/90adc050351c1d236ca23765874d54e2 to your computer and use it in GitHub Desktop.
Save chrisbrownie/90adc050351c1d236ca23765874d54e2 to your computer and use it in GitHub Desktop.
Compares a file to a given hash
function Compare-FileToHash {
<#
.SYNOPSIS
Compare-FileToHash - Compares a file to a given hash and returns a boolean of whether they match or not
.DESCRIPTION
This function will compare a file to a given hash (in string format) and
returns the boolean $true or $false depending on whether the hashes match.
Supported algorithms are all those supported by Get-FileHash.
.EXAMPLE
Compare-FileToHash -expectedHash F683E63A08F385F52E86990CEB62CF1374A23373 -algorithm SHA1 -Path $env:SYSTEMROOT\System32\shell32.dll
.LINK
https://flamingkeys.com/compare-file-hash-powershell/
.NOTES
Written by: Chris Brown
Find me on:
* My Blog: https://flamingkeys.com
* Twitter: https://twitter.com/chrisbrownie
* GitHub: https://github.com/chrisbrownie
#>
Param(
$expectedHash,
$algorithm="MD5",
$Path
)
$actualHash = (Get-FileHash -Path $Path -Algorithm $algorithm).Hash
New-Object -TypeName PSObject -Property @{
"Path" = $Path
"ExpectedHash" = $expectedHash
"ActualHash" = $actualHash
"Match" = if ($expectedHash -eq $actualHash) { $true } else { $false }
}
}
@ondrovic
Copy link

ondrovic commented Jan 8, 2022

Awesome little snippet tweaked it a bit, to keep items in order and also add a default -simple that just does true / false


param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$expectedHash,

        [Parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
        [string]$algorithm = "MD5",

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$path,

        [Parameter(Mandatory=$false)]
        [bool]$simple = $true
    )

    $actualHash = (Get-FileHash -Path $path -Algorithm $algorithm).Hash
    
    $Results=@()
    
    switch ($simple) {
        $true {
            if ($expectedHash -eq $actualHash) { Write-Host $true -ForegroundColor Green } else { Write-Host $false -ForegroundColor Red }
        }
        default {
        $hashProps = [ordered]@{
            "Path" = $path
            "Actual Hash" = $actualHash
            "Expected Hash" = $expectedHash
            "Matches" = if ($expectedHash -eq $actualHash) { $true } else { $false }
        }

        $Results += New-Object -TypeName PSObject -Property $hashProps

        $Results
       
        }
    }

@chrisbrownie
Copy link
Author

I like it...all except the use of Write-Host, which I don't like! Thanks for the contribution :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment