Quick code release
Get-Hash returns the MD5 or SHA256 hash of a file. (Note: Powershell 4.0 has a built-in command for this.)
Parameters
FilePath
The path to the file you wish to hash.
Usage
Inside of a powershell console enter the following:
"" -FilePath ""
Example:
&"C:\Scripts\Get-Hash.ps1" -FilePath "C:\FileToHash.xml"
Script
MD5
Param($FilePath)
if (-not (Test-Path $FilePath))
{
#File path not found. Not installed.
Write-Error "File does not exist"
}else
{
try
{
$FileStream = New-Object IO.FileStream $FilePath, "Open"
$MD5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$Hash = [System.BitConverter]::ToString($MD5.ComputeHash($FileStream))
Write-Output $Hash
}
catch
{
Write-Error $_.ToString()
}
}
SHA256
Param($FilePath)
if (-not (Test-Path $FilePath))
{
#File path not found. Not installed.
Write-Error "File does not exist"
}else
{
try
{
$FileStream = New-Object IO.FileStream $FilePath, "Open"
$SHA2 = new-object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider
$Hash = [System.BitConverter]::ToString($SHA2.ComputeHash($FileStream))
Write-Output $Hash
}
catch
{
Write-Error $_.ToString()
}
}