How to get an MD5 checksum in PowerShell

2020-01-25 03:17发布

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

16条回答
Summer. ? 凉城
2楼-- · 2020-01-25 04:09

Here are the two lines, just change "hello" in line #2:

PS C:\> [Reflection.Assembly]::LoadWithPartialName("System.Web")
PS C:\> [System.Web.Security.FormsAuthentication]::HashPasswordForStoringInConfigFile("hello", "MD5")
查看更多
爷、活的狠高调
3楼-- · 2020-01-25 04:09

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.

查看更多
聊天终结者
4楼-- · 2020-01-25 04:09

This becomes a one-liner if you download File Checksum Integrity Verifier (FCIV) from Microsoft.

I downloaded FCIV from here: Availability and description of the File Checksum Integrity Verifier utility

Run the following command. I had ten files to check.

Get-ChildItem WTAM*.tar | % {.\fciv $_.Name}
查看更多
▲ chillily
5楼-- · 2020-01-25 04:10

There are a lot of examples online using ComputeHash(). My testing showed this was very slow when running over a network connection. The snippet below runs much faster for me, however your mileage may vary:

$md5 = [System.Security.Cryptography.MD5]::Create("MD5")
$fd = [System.IO.File]::OpenRead($file)
$buf = New-Object byte[] (1024*1024*8) # 8 MB buffer
while (($read_len = $fd.Read($buf,0,$buf.length)) -eq $buf.length){
    $total += $buf.length
    $md5.TransformBlock($buf,$offset,$buf.length,$buf,$offset)
    Write-Progress -Activity "Hashing File" `
       -Status $file -percentComplete ($total/$fd.length * 100)
}

# Finalize the last read
$md5.TransformFinalBlock($buf, 0, $read_len)
$hash = $md5.Hash

# Convert hash bytes to a hexadecimal formatted string
$hash | foreach { $hash_txt += $_.ToString("x2") }
Write-Host $hash_txt
查看更多
登录 后发表回答