PowerShell Function: Get-MD5Checksum

    ##--------------------------------------------------------------------------
    ##  FUNCTION.......:  Get-MD5Checksum
    ##  PURPOSE........:  Generates an MD5 checksum for the specified file.
    ##  REQUIREMENTS...:  PowerShell v2
    ##  NOTES..........:  
    ##--------------------------------------------------------------------------
    Function Get-MD5Checksum {
        <#
        .SYNOPSIS
         Generates an MD5 checksum for the specified file.
        .DESCRIPTION
         This function uses the 
         System.Security.Cryptography.MD5CryptoServiceProvider .NET class to
         generate and retun an MD5 checksum for the specified file.
        .PARAMETER FileName
         The filename including path for which to generate the MD5 sum.

         ALIAS: -f
        .EXAMPLE
         C:\PS>Get-MD5Checksum c:\test.txt

         This will return an MD5 checksum for the file c:\test.txt

        .EXAMPLE
         C:\PS>"C:\TEST\test.csv" | Get-MD5Checksum

         This will also return an MD5 checksum for the file c:\test.txt, passing
         the FileName to the function using pipelining.

        .NOTES
         NAME......:  Get-MD5Checksum
         AUTHOR....:  Joe Glessner
         LAST EDIT.:  14MAY12
         CREATED...:  11APR08
        .LINK
         https://joeit.wordpress.com/
        #>

        Param([Parameter(Mandatory = $True,
            ValueFromPipeLine = $True,
            Position = 0)]
            [Alias('f')]
            [String]$FileName
        )#END: Param

        $MD5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
        If([System.IO.File]::Exists($FileName)) {
            $FileStream = New-Object System.IO.FileStream($FileName,`
            [System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,`
            [System.IO.FileShare]::ReadWrite)
            [byte[]]$ByteSum = $MD5.ComputeHash($FileStream)
            $Sum = ([System.Bitconverter]::ToString($ByteSum)).Replace("-","")
            $FileStream.Close()
        }#END: If([System.IO.File]::Exists($fileName))
        Else {
            $Sum = "ERROR: $FileName Not Found"
        }#END: Else
        Return $Sum
    }#END: Function Get-MD5Checksum

One Response to PowerShell Function: Get-MD5Checksum

  1. Gary O'Keefe says:

    Cheers for that – I was having a real problem checksumming some of the large models (2Gb+) we have kicking around. This (especially the correct parameters for opening the FileStream) was a real help.

Leave a comment