schittli
3/22/2013 - 6:30 PM

PowerShell script to compute an MD5 hash for files

PowerShell script to compute an MD5 hash for files

# Copyright (c) 2013 Atif Aziz. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[CmdletBinding()]
param(
    [parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
    [IO.FileInfo[]]$file)
BEGIN { $md5 = [Security.Cryptography.MD5]::Create() }
PROCESS
{
    foreach ($f in $file) 
    {
        try
        {
            $fs = [IO.File]::OpenRead($f.FullName)
            $bs = New-Object IO.BufferedStream($fs, (64 * 1024))
            $hash = [BitConverter]::ToString($md5.ComputeHash($bs)).Replace('-', '')
            # Add-Member -InputObject $F -PassThru -MemberType NoteProperty -Name Hash -Value $Hash
            New-Object PSObject -Property @{ File = $f; Hash = $hash }
        }
        finally
        {
            if ($bs -ne $null) { $bs.Dispose() }
            if ($fs -ne $null) { $fs.Dispose() }
        }
     }
}
END { $md5.Dispose() }

# Usage:
# dir | .\md5.ps1