Windows: Verify File Checksums

Windows doesn’t provide a brilliant utility for verifying the checksum value on files (typically a task I want to perform on files downloaded from the internet). Well… in fact there is a utility, however the biggest drawn back is how it only generates the hash of the file while stopping short of comparing the file hash to the checksum provided by the website. That’s a feature I believe deserves support in a checksum utility, so I’ve created my own in a Powershell script.

## File Checksum Verifier
## Calculate a file's checksum, chosen from a list of supported hashes, then compare to a provided checksum value

param ($path, $hash, $checksum)

$HelpKeywords = @("-h", "-help", "-?")
if ($HelpKeywords -contains $args[0])
{
  Write-Output "verify-checksum -path <path to target file> -hash <SHA1|SHA256|SHA512|MD5> -checksum <provided checksum>"
  exit
}

Write-Output "File Checksum Verifier"

if (!$path) {$TargetFilePath = $(read-host "Path to file").Replace("`"","")} else { $TargetFilePath = $path }

$SupportedHashes = @("SHA1", "SHA256", "SHA512", "MD5")
if ($SupportedHashes -notcontains $hash) {
  $HashSelectionMenu = "
[1] SHA1
[2] SHA256
[3] SHA512
[4] MD5
"
  $HashSelectionPrompt = "Select hash to use (type ? for help)[MD5]"
  $HashSelectionMenu
  do {
    try {
      $HashMenuSelection = read-host "$HashSelectionPrompt"
	  if ($HashMenuSelection -eq "") {$HashMenuSelection=4}
	  if (($HashMenuSelection -ge 1 -and $HashMenuSelection -le 4) -and $HashMenuSelection -as [int])
	  {
  	    $NoError=$true
	  }
	  else
	  {
	    if ($HashMenuSelection -eq "?")
	    {
	      $HashSelectionMenu
	    }
	    else
	    {
  	      "Not a menu selection!`n"
	    }
	    throw "bad value"
	  }
    }
    catch {$NoError = $false}
  }
  until ($NoError)
  $SelectedHash = switch($HashMenuSelection)
  {
    1 {"SHA1"}
    2 {"SHA256"}
    3 {"SHA512"}
    4 {"MD5"}
    default {"MD5"}
  }
}
else
{
  $SelectedHash = $hash
}

if (!$checksum) {$ProvidedChecksum = read-host "Provided Checksum"} else { $ProvidedChecksum = $checksum }

$FileChecksum = $(get-filehash $TargetFilePath -algorithm $SelectedHash).hash
Write-Output "File Checksum: $FileChecksum"

$ChecksumChecksOut = "$FileChecksum" -eq "$ProvidedChecksum"

Write-Output "Checksum matches: $ChecksumChecksOut"

I’ve then placed this file in C:\Program Files\Scripts and added that directory to my system Path variable (see how in this article). Now I simply call the script with verify-checksum. The script accepts the following options: -path for the full path to the file you want a checksum of, -hash to specify which hash to use on the file (one of: SHA1, SHA256, SHA512, or MD5), and -checksum for the checksum value supplied by the website you got the file from. Or, instead of passing everything to the command during the call, it will recognize any and all options missing and prompt you for each one that is still needed (or that did not match an accepted value).