How to get an MD5 checksum in PowerShell

后端 未结 17 1626
夕颜
夕颜 2020-11-28 01:14

I would like to calculate an MD5 checksum of some content. How do I do this in PowerShell?

17条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 01:38

    Here's a function I use that handles relative and absolute paths:

    function md5hash($path)
    {
        $fullPath = Resolve-Path $path
        $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
        $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
        try {
            [System.BitConverter]::ToString($md5.ComputeHash($file))
        } finally {
            $file.Dispose()
        }
    }
    

    Thanks to @davor above for the suggestion to use Open() instead of ReadAllBytes() and to @jpmc26 for the suggestion to use a finally block.

提交回复
热议问题