Generating A Media Hash using Powershell

Another quick one while I’m on Powershell 🙂

Here’s a script to generate a hash of a media file:

#Generate MD5 Hash of item
function To-Byte-Array
        {
            param (
			[CmdletBinding()]
			[Parameter(Mandatory = $true)]
			[AllowEmptyString()]
			[AllowEmptyCollection()]
			[AllowNull()]
			[Object]
			$InputStream)
			
            $InputStream.Position = 0
            $buffer = New-Object byte[] $InputStream.Length
			$i = 0
			For ($totalBytesCopied=0; $totalBytesCopied -lt $InputStream.Length; $i++) {
				$totalBytesCopied += $InputStream.Read($buffer, $totalBytesCopied, $InputStream.Length - $totalBytesCopied)
			}
            
			$buffer
        }

$item = Get-Item master: -ID "{20AA9D26-F1D6-43DB-B8A8-21EC04A5A4CB}" -Language de-DE
	$mediaItem = New-Object Sitecore.Data.Items.MediaItem($item)
	$media = [Sitecore.Resources.Media.MediaManager]::GetMedia($mediaItem)
	$stream = $media.GetStream().Stream
	try {
		$bytes = To-Byte-Array $stream
	}
	finally
    {
        if ($null -ne $stream -and $stream -is [System.IDisposable])
        {
            $stream.Dispose()
        }
    }
	
	$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
	$hash = [System.BitConverter]::ToString($md5.ComputeHash($bytes))
	
	Write-Host $hash
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s