Monday, 14 April 2014

Calculate MD5 or SHA1 Hash Values from PowerShell

I recently had to rebuild my machine due to a hard disk failure, which meant that I've been downloading quite a bit of stuff from MSDN and since I've been doing working with PowerShell quite a bit, I thought I'd better write a couple of functions to check the hashes of stuff I've downloaded.

MD5
function MD5
{
 param ( [string] $inputFile )
 
 if($inputFile) 
 {
  try 
  {
   $md5 = new-object System.Security.Cryptography.MD5CryptoServiceProvider
   $file = [System.IO.File]::ReadAllBytes($inputFile)
   $hash = $md5.ComputeHash($file)
   $hash | %{write-host $_.tostring("x2") -nonewline}; ""
  }
  catch
  {
   Write-Error $($_.Exception.Message)
  }
 }
 else
 {
  Write-Host "Please enter the full path to the file you want to calculate the hash for"
 }
}

MD5 C:\downloads\linux.iso

SHA1
function SHA1
{
 param ( [string] $inputFile )
 
 if($inputFile) 
 {
  try
  {
   $sha1 = new-object System.Security.Cryptography.Sha1Managed
   $file = [System.IO.File]::OpenRead($inputFile)
   $hash = $sha1.ComputeHash($file)
   $hash | %{write-host $_.tostring("x2") -nonewline}; ""
  }
  catch
  {
   Write-Error $($_.Exception.Message)
  }
  finally
  {
   $file.Close() 
  }
 }
 else
 {
  Write-Host "Please enter the full path to the file you want to calculate the sha1 hash for."
 }
}

SHA1 C:\downloads\windows.iso

See man profile for details on how to add these to your profile so that the functions are available every time PowerShell is started.

No comments:

Post a Comment