Windows Vista Forums

HowTo: Create an MD5 of File
  1. #1


    Brandon Shell Guest

    HowTo: Create an MD5 of File

    Goal: I want to be able to get the MD5 of file and store it. Then use it to
    verify a file on a remote server is exactly the same.




      My System SpecsSystem Spec

  2. #2


    Brandon Shell Guest

    Re: HowTo: Create an MD5 of File

    Ok... I got the MD5 from file (kinda simple really.)

    The problem is that this returns a Byte[]. Compare-Object doesn't like this
    for some reason and for seemingly obvious reasons .ToString() doesn't
    convert it correctly.

    Any Ideas?

    "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    news:%23ciNSGhGHHA.1804@TK2MSFTNGP02.phx.gbl...
    > Goal: I want to be able to get the MD5 of file and store it. Then use it
    > to verify a file on a remote server is exactly the same.



      My System SpecsSystem Spec

  3. #3


    Brandon Shell Guest

    Re: HowTo: Create an MD5 of File

    Ok... ignore me... I'm apparently prematurely asking for help. I figured it
    out.

    I didn't realize that compare-objects doesn't return anything if the objects
    are the same... silly me.. I was expecting a $true or $false.

    "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    news:O8szF3hGHHA.3468@TK2MSFTNGP04.phx.gbl...
    > Ok... I got the MD5 from file (kinda simple really.)
    >
    > The problem is that this returns a Byte[]. Compare-Object doesn't like
    > this for some reason and for seemingly obvious reasons .ToString() doesn't
    > convert it correctly.
    >
    > Any Ideas?
    >
    > "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    > news:%23ciNSGhGHHA.1804@TK2MSFTNGP02.phx.gbl...
    >> Goal: I want to be able to get the MD5 of file and store it. Then use it
    >> to verify a file on a remote server is exactly the same.

    >



      My System SpecsSystem Spec

  4. #4


    Bruce Payette [MSFT] Guest

    Re: HowTo: Create an MD5 of File

    Cribbing from:

    http://blog.stevex.net/index.php/c-c...5-hash-string/

    The C# snippet is easily translated into PowerShell:

    function Get-Md5
    {
    param ($inputString, $file, [switch] $base64)

    if ($file)
    {
    $input = get-content -encoding byte -readcount -1 $file
    }
    else
    {
    $input = [System.Text.Encoding]::Unicode.GetBytes($inputString)
    }
    $md5 = [System.Security.Cryptography.MD5]::Create()
    $output = $md5.ComputeHash($input)
    if ($base64)
    {
    [System.Convert]::ToBase64String($output)
    }
    else
    {
    $sb = new-object Text.StringBuilder
    foreach ($b in $output)
    {
    [void] $sb.Append($b.ToString("X2"));
    }
    $sb.ToString()
    }
    }

    So when you're looking for a way to do something in PowerShell, C# and
    VB.Net examples are also very useful :-)

    -bruce

    --
    Bruce Payette [MSFT]
    Windows PowerShell Technical Lead
    Microsoft Corporation
    This posting is provided "AS IS" with no warranties, and confers no rights.

    Visit the Windows PowerShell Team blog at:
    http://blogs.msdn.com/PowerShell
    Visit the Windows PowerShell ScriptCenter at:
    http://www.microsoft.com/technet/scr.../hubs/msh.mspx
    My Book: http://manning.com/powershell

    "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    news:O8szF3hGHHA.3468@TK2MSFTNGP04.phx.gbl...
    > Ok... I got the MD5 from file (kinda simple really.)
    >
    > The problem is that this returns a Byte[]. Compare-Object doesn't like
    > this for some reason and for seemingly obvious reasons .ToString() doesn't
    > convert it correctly.
    >
    > Any Ideas?
    >
    > "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    > news:%23ciNSGhGHHA.1804@TK2MSFTNGP02.phx.gbl...
    >> Goal: I want to be able to get the MD5 of file and store it. Then use it
    >> to verify a file on a remote server is exactly the same.

    >




      My System SpecsSystem Spec

  5. #5


    Sung M Kim Guest

    Re: HowTo: Create an MD5 of File


    Brandon Shell wrote:
    > Ok... ignore me... I'm apparently prematurely asking for help. I figured it
    > out.
    >

    well i had found the blog post for Get-MD5 by Marcel on old monad blog
    site http://blogs.msdn.com/monad/archive/...13/465250.aspx .
    I just could not ignore your post!


      My System SpecsSystem Spec

  6. #6


    Brandon Shell Guest

    Re: HowTo: Create an MD5 of File

    Thanks Bruce... I actually use that to get mine working. Mine is much
    simpler... but I dont care about getting it to a string or file size.

    "Bruce Payette [MSFT]" <brucepay@microsoft.com> wrote in message
    news:usgAgKiGHHA.3464@TK2MSFTNGP05.phx.gbl...
    > Cribbing from:
    >
    > http://blog.stevex.net/index.php/c-c...5-hash-string/
    >
    > The C# snippet is easily translated into PowerShell:
    >
    > function Get-Md5
    > {
    > param ($inputString, $file, [switch] $base64)
    >
    > if ($file)
    > {
    > $input = get-content -encoding byte -readcount -1 $file
    > }
    > else
    > {
    > $input = [System.Text.Encoding]::Unicode.GetBytes($inputString)
    > }
    > $md5 = [System.Security.Cryptography.MD5]::Create()
    > $output = $md5.ComputeHash($input)
    > if ($base64)
    > {
    > [System.Convert]::ToBase64String($output)
    > }
    > else
    > {
    > $sb = new-object Text.StringBuilder
    > foreach ($b in $output)
    > {
    > [void] $sb.Append($b.ToString("X2"));
    > }
    > $sb.ToString()
    > }
    > }
    >
    > So when you're looking for a way to do something in PowerShell, C# and
    > VB.Net examples are also very useful :-)
    >
    > -bruce
    >
    > --
    > Bruce Payette [MSFT]
    > Windows PowerShell Technical Lead
    > Microsoft Corporation
    > This posting is provided "AS IS" with no warranties, and confers no
    > rights.
    >
    > Visit the Windows PowerShell Team blog at:
    > http://blogs.msdn.com/PowerShell
    > Visit the Windows PowerShell ScriptCenter at:
    > http://www.microsoft.com/technet/scr.../hubs/msh.mspx
    > My Book: http://manning.com/powershell
    >
    > "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    > news:O8szF3hGHHA.3468@TK2MSFTNGP04.phx.gbl...
    >> Ok... I got the MD5 from file (kinda simple really.)
    >>
    >> The problem is that this returns a Byte[]. Compare-Object doesn't like
    >> this for some reason and for seemingly obvious reasons .ToString()
    >> doesn't convert it correctly.
    >>
    >> Any Ideas?
    >>
    >> "Brandon Shell" <tshell.mask@gmail.com> wrote in message
    >> news:%23ciNSGhGHHA.1804@TK2MSFTNGP02.phx.gbl...
    >>> Goal: I want to be able to get the MD5 of file and store it. Then use it
    >>> to verify a file on a remote server is exactly the same.

    >>

    >
    >



      My System SpecsSystem Spec

  7. #7


    Maximilian Hänel Guest

    Re: HowTo: Create an MD5 of File

    Hi Sung,

    > well i had found the blog post for Get-MD5 by Marcel on old monad blog
    > site http://blogs.msdn.com/monad/archive/...13/465250.aspx .
    > I just could not ignore your post!


    Nice! I modified the script a little bit so it handles powershell paths
    correctly. It now also supports wildcards, piplining and an optional
    format specifier:

    PS > Get-MD5 *.ps1
    PS > Get-MD5 *.ps1 -format D3
    PS > ls -Recurse | Get-MD5
    PS > ls -Recurse | Get-MD5 | Select Text, Path | ft -auto

    cu

    Max

    # Get-MD5.ps1
    param(
    [string]$path,
    [string]$format="X2")
    begin
    {
    $hashAlgorithm = [System.Security.Cryptography.MD5]::Create()

    function ProcessObject($object)
    {
    if($object -is [IO.FileInfo])
    {
    ProcessFile $object.FullName
    }
    elseif($object -is [IO.DirectoryInfo])
    {
    # skip directories...
    }
    elseif($object -and $object.Path)
    {
    ProcessFile $object.Path
    }
    elseif($object)
    {
    ProcessFile $object
    }
    }
    function ProcessFile([string]$filesToProcess)
    {
    foreach($pathInfo in (resolve-path $filesToProcess))
    {
    $stream = $null;
    trap
    {
    ## We have to be sure that we close the file stream
    ## if any exceptions are thrown.
    if ($stream -ne $null)
    {
    $stream.Close();
    }
    }

    $file=[System.IO.FileInfo]$pathInfo.Path

    $stream = $file.OpenRead();
    $hashByteArray = $hashAlgorithm.ComputeHash($stream);
    $stream.Close();

    $result=1 | Select Text, Bytes, Path
    $result.Text=[String]::Join("", ($hashByteArray | %{
    "{0:$format}" -f $_ }) )
    $result.Bytes=$hashByteArray
    $result.Path=$file.FullName

    $result
    }
    }
    }
    process
    {
    ProcessObject $_
    }
    end
    {
    ProcessObject $path
    }
    #eof

      My System SpecsSystem Spec

  8. #8


    Brandon Shell Guest

    Re: HowTo: Create an MD5 of File

    May I suggest that this get included in the Powershell Community Extensions?
    Its very useful. Unfortunately for me I got this after I had written my
    own... but I like yours better

    "Maximilian Hänel" <ngSpam@smjh.de> wrote in message
    news:OgyoaxkGHHA.3780@TK2MSFTNGP02.phx.gbl...
    > Hi Sung,
    >
    >> well i had found the blog post for Get-MD5 by Marcel on old monad blog
    >> site http://blogs.msdn.com/monad/archive/...13/465250.aspx .
    >> I just could not ignore your post!

    >
    > Nice! I modified the script a little bit so it handles powershell paths
    > correctly. It now also supports wildcards, piplining and an optional
    > format specifier:
    >
    > PS > Get-MD5 *.ps1
    > PS > Get-MD5 *.ps1 -format D3
    > PS > ls -Recurse | Get-MD5
    > PS > ls -Recurse | Get-MD5 | Select Text, Path | ft -auto
    >
    > cu
    >
    > Max
    >
    > # Get-MD5.ps1
    > param(
    > [string]$path,
    > [string]$format="X2")
    > begin
    > {
    > $hashAlgorithm = [System.Security.Cryptography.MD5]::Create()
    >
    > function ProcessObject($object)
    > {
    > if($object -is [IO.FileInfo])
    > {
    > ProcessFile $object.FullName
    > }
    > elseif($object -is [IO.DirectoryInfo])
    > {
    > # skip directories...
    > }
    > elseif($object -and $object.Path)
    > {
    > ProcessFile $object.Path
    > }
    > elseif($object)
    > {
    > ProcessFile $object
    > }
    > }
    > function ProcessFile([string]$filesToProcess)
    > {
    > foreach($pathInfo in (resolve-path $filesToProcess))
    > {
    > $stream = $null;
    > trap
    > {
    > ## We have to be sure that we close the file stream
    > ## if any exceptions are thrown.
    > if ($stream -ne $null)
    > {
    > $stream.Close();
    > }
    > }
    >
    > $file=[System.IO.FileInfo]$pathInfo.Path
    >
    > $stream = $file.OpenRead();
    > $hashByteArray = $hashAlgorithm.ComputeHash($stream);
    > $stream.Close();
    >
    > $result=1 | Select Text, Bytes, Path
    > $result.Text=[String]::Join("", ($hashByteArray | %{
    > "{0:$format}" -f $_ }) )
    > $result.Bytes=$hashByteArray
    > $result.Path=$file.FullName
    >
    > $result
    > }
    > }
    > }
    > process
    > {
    > ProcessObject $_
    > }
    > end
    > {
    > ProcessObject $path
    > }
    > #eof



      My System SpecsSystem Spec

  9. #9


    Maximilian Hänel Guest

    Re: HowTo: Create an MD5 of File

    Hi Bruce,

    > $input = get-content -encoding byte -readcount -1 $file


    Don't try this at home! ;-)
    Reading the whole file into memory not only consumes lots of memory, it
    might even fail on very large files.

    cu

    Max

      My System SpecsSystem Spec

  10. #10


    Sung M Kim Guest

    Re: HowTo: Create an MD5 of File


    Maximilian Hänel wrote:
    > Hi Sung,
    >
    > > well i had found the blog post for Get-MD5 by Marcel on old monad blog
    > > site http://blogs.msdn.com/monad/archive/...13/465250.aspx .
    > > I just could not ignore your post!

    >
    > Nice! I modified the script a little bit so it handles powershell paths
    > correctly. It now also supports wildcards, piplining and an optional
    > format specifier:


    Uhm.. Come to think of it, i did modify that Get-MD5 script a while
    back
    I had uploaded the my modification on www.CodePlex.com/psObject ...
    Silly me.
    My version supports checks against [FileInfo] though.. although it
    supports pipeline input.
    Looks quite similiar


    # Author: Marcel Ortiz
    # Modified by: Sung Kim
    # Reference: http://blogs.msdn.com/monad/archive/...13/465250.aspx
    # Description: Calculates the hash of a file and returns it as a
    string.
    # NOTE: Modified to act like a cmdlet to process pipeline input as well
    # Original Get-MD5 by Marcel returns a string while this function
    # returns a byte array per $file or a pipeline input
    function Get-MD5 {
    param([System.IO.FileInfo] $file)

    begin {
    function DisplayUsage {
    $private:UsageString = 'USAGE: Get-MD5 [System.IO.FileInfo]`n'
    $private:UsageString += 'Examples:`n'
    $private:UsageString += '1) Get the MD5 bytes for the specified
    argument`n'
    $private:UsageString += '`tGet-MD5 (Get-Item file_name)`n'
    $private:UsageString += '2) Get MD5 bytes for pipeline input`n'
    $private:UsageString += '`tls | Get-MD5`n'
    $private:UsageString += '3) How to check(a quick way) if two files
    have same MD5 hash values`n'
    $private:UsageString += '`tif (Compare-Object (get-md5 (gi
    fileName1)) (get-md5 (gi fileName2))) `n'
    $private:UsageString += '`t{ "different" } else { "same" }'
    Write-Host -ForegroundColor "White" $private:UsageString
    }

    function ComputeHash([System.IO.FileInfo]$fileInfo) {
    $PRIVATE:stream = $null;
    # A type Shortcut for MD5CryptoServiceProvider type
    # Reference:
    http://blogs.msdn.com/powershell/arc...12/663540.aspx
    $PRIVATE:cryptoServiceProvider =
    [System.Security.Cryptography.MD5CryptoServiceProvider];
    $PRIVATE:hashAlgorithm = new-object $PRIVATE:cryptoServiceProvider
    $PRIVATE:stream = $fileInfo.OpenRead();
    $PRIVATE:hashByteArray =
    $PRIVATE:hashAlgorithm.ComputeHash($PRIVATE:stream);
    $PRIVATE:stream.Close();

    # We have to be sure that we close the file stream
    # if any exceptions are thrown.
    trap {
    if ($PRIVATE:stream -ne $null) {
    $PRIVATE:stream.Close();
    }
    break;
    }

    return $PRIVATE:hashByteArray;
    }

    }

    process {
    if ($_ -is [IO.FileInfo]) {
    ComputeHash($_)
    }
    }

    end {
    # Check if "-?", "-h" or "-help" argument has been passed
    if ($args[0] -match '-(\?|(h|(help)))') {
    DisplayUsage
    return;
    }

    if ($file) {
    ComputeHash($file)
    }

    trap {
    DisplayUsage;
    break;
    }
    }
    }


      My System SpecsSystem Spec

Page 1 of 4 123 ... LastLast
HowTo: Create an MD5 of File problems?

Similar Threads
Thread Thread Starter Forum Replies Last Post
Howto create custom objects/classes Carson PowerShell 2 28 Mar 2008
Vista RAM Disk howto create? qa4eve Vista performance & maintenance 4 12 Jan 2008
HowTo: Get Text from a file and put in a string. Brandon Shell PowerShell 4 22 Dec 2006
HowTo: Create PoSH Snap-ins for Complete nubs Brandon Shell PowerShell 10 18 Dec 2006
HowTo: Create Windows Form without Stopping the Script from Processing Brandon Shell PowerShell 7 15 Sep 2006