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.

Translate to de es fr it pt ja

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

The author does not allow comments to this entry

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Markdown format allowed
Form options