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


当前回答

从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)))

其他回答

如果从Microsoft下载文件校验和完整性验证器(FCIV),这将变成一行程序。

我从这里下载了FCIV: 文件校验和完整性验证工具的可用性和说明

执行如下命令。我有十份文件要检查。

Get-ChildItem WTAM*.tar | % {.\fciv $_.Name}

下面是我用来获取给定字符串的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")}) 

这里有两行,只需在第2行中更改“hello”:

PS C:\> [Reflection.Assembly]::LoadWithPartialName("System.Web")
PS C:\> [System.Web.Security.FormsAuthentication]::HashPasswordForStoringInConfigFile("hello", "MD5")

下面是我使用的处理相对路径和绝对路径的函数:

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()
    }
}

感谢@davor上面建议使用Open()而不是ReadAllBytes(),并感谢@jpmc26建议使用finally块。

从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)))