PoshCode Logo PowerShell Code Repository

Hash Checker by Joel Bennett 7 years ago (modification of post by Joel Bennett view diff)
View followups from eeefdf, aaaaa, coleangelz, Joel Bennett and babel | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/989"></script>download | new post

Check md5/sha1/etc hashes

  1. #.Synopsis
  2. #   Test the HMAC hash(es) of a file
  3. #.Description
  4. #   Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash
  5. #.Example
  6. #   Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5
  7. #
  8. #   Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name
  9. #   and take the hash of the file (using the extension of the HashFile as the Type of Hash).
  10. #
  11. #.Example
  12. #   Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5
  13. #
  14. #   Takes the MD5 hash and compares it to the provided hash
  15. #
  16. #.Example
  17. #   Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517
  18. #
  19. #   Tests all of the hashes against the provided (Sha1) hash
  20. #
  21. function Test-Hash {
  22. #[CmdletBinding(DefaultParameterSetName="NoExpectation")]
  23. PARAM(
  24.    #[Parameter(Position=0,Mandatory=$true)]
  25.    [string]$FileName
  26. ,
  27.    #[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
  28.    [string]$ExpectedHash = $(if($HashFileName){  ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0]  })
  29. ,
  30.    #[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
  31.    [string]$HashFileName
  32. ,
  33.    #[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
  34.    [string[]]$TypeOfHash = $(if($HashFileName){  
  35.                           [IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
  36.                  } else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
  37. )
  38. $ofs=""
  39.   $hashes = @{}
  40.   foreach($Type in $TypeOfHash) {
  41.     [string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
  42.       $Type
  43.     ).ComputeHash(
  44.       [IO.File]::ReadAllBytes( (Convert-Path $FileName) )
  45.     ) | ForEach { "{0:x2}" -f $_ }
  46.     $hashes.$Type = $hash
  47.   }
  48.  
  49.   if($ExpectedHash) {
  50.     ($hashes.Values -eq $hash).Count -ge 1
  51.   } else {
  52.     foreach($hash in $hashes.GetEnumerator()) {
  53.       "{0,-8}{1}" -f $hash.Name, $hash.Value
  54.     }        
  55.   }
  56. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me