我想计算一些内容的MD5校验和。如何在PowerShell中做到这一点?


当前回答

如果你正在使用PowerShell社区扩展,有一个Get-Hash命令可以很容易地做到这一点:

C:\PS> "hello world" | Get-Hash -Algorithm MD5


Algorithm: MD5


Path       :
HashString : E42B054623B3799CB71F0883900F2764

其他回答

下面是我用来获取给定字符串的MD5的代码片段:

$text = "text goes here..."
$md5  = [Security.Cryptography.MD5CryptoServiceProvider]::new()
$utf8 = [Text.UTF8Encoding]::UTF8
$bytes= $md5.ComputeHash($utf8.GetBytes($text))
$hash = [string]::Concat($bytes.foreach{$_.ToString("x2")}) 

另一个早在2003年就默认安装在Windows中的内置命令是Certutil,当然也可以从PowerShell调用它。

CertUtil -hashfile file.foo MD5

(注意:MD5应该全部大写以获得最大的健壮性)

从PowerShell版本4开始,使用Get-FileHash cmdlet可以很容易地实现文件的开箱即用:

Get-FileHash <filepath> -Algorithm MD5

这当然是更可取的,因为它避免了注释中指出的旧PowerShell解决方案所提供的问题(使用流,关闭它,并支持大文件)。

如果内容是字符串:

$someString = "Hello, World!"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = New-Object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))

对于较旧的PowerShell版本

如果内容为文件:

$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))

现在有一个Get-FileHash函数,非常方便。

PS C:\> Get-FileHash C:\Users\Andris\Downloads\Contoso8_1_ENT.iso -Algorithm SHA384 | Format-List

Algorithm : SHA384
Hash      : 20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E508E2EBBC9D3C96F21FA3
Path      : C:\Users\Andris\Downloads\Contoso8_1_ENT.iso

只需将SHA384更改为MD5即可。

示例来自PowerShell 5.1的官方文档。文档中有更多示例。

这个网站有一个例子:使用Powershell进行MD5校验和。它使用. net框架实例化MD5哈希算法的实例来计算哈希值。

下面是本文的代码,包含Stephen的注释:

param
(
  $file
)

$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open,
    [System.IO.FileAccess]::Read)

$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | % { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()

$stream.Dispose()