Skip to content

Instantly share code, notes, and snippets.

@victorvogelpoel
Last active December 23, 2015 13:29
Show Gist options
  • Save victorvogelpoel/6642709 to your computer and use it in GitHub Desktop.
Save victorvogelpoel/6642709 to your computer and use it in GitHub Desktop.
# Victor Vogelpoel
#
# Disclaimer
# This script is provided AS IS without warranty of any kind. I disclaim all implied warranties including, without limitation,
# any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or
# performance of the sample scripts and documentation remains with you. In no event shall I be liable for any damages whatsoever
# (including, without limitation, damages for loss of business profits, business interruption, loss of business information,
# or other pecuniary loss) arising out of the use of or inability to use the script or documentation.
function Get-MD5
{
[CmdletBinding(SupportsShouldProcess=$false)]
param
(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="file(s) to create hash for")]
[Alias("File", "Path", "PSPath", "String")]
[ValidateNotNull()]
$InputObject
)
begin
{
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider]
$hashAlgorithm = new-object $cryptoServiceProvider
}
process
{
$hashByteArray = ""
$item = Get-Item $InputObject -ErrorAction SilentlyContinue
if ($item -is [System.IO.DirectoryInfo]) { throw "Cannot create hash for directory" }
if ($item) { $InputObject = $item }
if ($InputObject -is [System.IO.FileInfo])
{
$stream = $null;
$hashByteArray = $null
try
{
$stream = $InputObject.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
}
finally
{
if ($stream -ne $null)
{
$stream.Close();
}
}
}
else
{
$utf8 = new-object -TypeName "System.Text.UTF8Encoding"
$hashByteArray = $hashAlgorithm.ComputeHash($utf8.GetBytes($InputObject.ToString()));
}
Write-Output ([BitConverter]::ToString($hashByteArray)).Replace("-","")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment