November 18, 2011

Powershell - Generate MD5 or SHA File Hash

There are lots Powershell file hashing functions available in the Blogosphere. Mine is nothing new. Inspiration was taken from a number of sources and modified to suit my needs.

Script "Get-FileHash.ps1"
function Get-FileHash
{
<#
.Synopsis
Compute the hash value of a file based on the MD5, SHA1 or SHA256 algorithms.
.Description
Returns a string that represents the hash
.Parameter File
The file to process. Either piped from Get-ChildItem or the fullpath as a string
.Parameter Algorithm
MD5, SHA1 or SHA256
.Example
dir c:\temp | ?{-not $_.PSIsContainer} | Get-FileHash
#>
[CmdletBinding(
SupportsShouldProcess=$False,
SupportsTransactions=$False,
ConfirmImpact="Low",
DefaultParameterSetName="")]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[System.IO.FileSystemInfo]$file
,
[Parameter(Position=1,Mandatory=$false)]
[ValidateSet("MD5","SHA1","SHA256")]
[string]$Algorithm="MD5"
)
BEGIN{}
PROCESS{

# Silently ignore folders
if(($file -as [System.IO.FileInfo]) -eq $null){
Write-Debug "Unsupported input object - '$($File.Fullname)'"
return        
}

$Property=@{
Filename = $file.Name
Fullname = $file.Fullname
Hash = ""
Result = ""
Algorithm = $Algorithm
}

Switch($Algorithm){
"MD5" {
$alg = new-object System.Security.Cryptography.MD5CryptoServiceProvider
}

"SHA1"{
$alg = new-object System.Security.Cryptography.SHA1CryptoServiceProvider
}

"SHA256"{
$alg = new-object System.Security.Cryptography.SHA256CryptoServiceProvider
}
}#switch

try{

$stream = $file.OpenRead()
$HashBuilder = New-Object System.Text.StringBuilder
$alg.ComputeHash($stream) | ForEach-Object { [void] $HashBuilder.Append($_.ToString("x2")) }
$Property.Item("Hash") = $HashBuilder.ToString()
$stream.close()

$Property.Item("Result") = "Success"

}catch{
if ($stream -ne $null){ $stream.Close() }
$Property.Item("Result") = "Error::Failed, message '$_'"
}


New-Object -Typename PSObject -Property $Property
}
END{}

}

No comments:

Post a Comment