Skip to content

Powershell - Compare file hash with existing hash file (checksum, SHA1) to validate binary file integrity

A quick win you should add to your power shell scripts whenever you execute a binary file by doing an integrity check based on checksums.

$pathToBinaryFile = "/your/file.path"
$pathToSha1File = $($pathToBinaryFile + ".sha1")

If (test-path $pathToBinaryFile) {
    $calculatedFileHash = Get-FileHash -LiteralPath $pathToBinaryFile -Algorithm SHA1
    $sha1FileContent = Get-Content $pathToSha1File 

    Write-Host ":: Checking file integrity."
    #we are expecting a sha1 file with one line of content.
    #   this one line should look like:<file name>\t<sha1 sum>
    #we are exploding the expected content by " "
    #   first array entry is <file name>
    #   second array entry is \t
    #   third array entry is <sha1 sum>
    $expectedFileHash = $sha1FileContent.Split(" ")[2]

    If ($expectedFileHash -ne $calculatedFileHash.HASH) {
        Write-Host $("   Binary file integrity check failed. Expected checksum >>" + $expectedFileHash + "<<, current checksum >>" + $calculatedFileHash.HASH + "<<.")
    }
}

A bit more advanced script can be found here in my examples collection.