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


当前回答

这将返回远程计算机上文件的MD5哈希值:

Invoke-Command -ComputerName RemoteComputerName -ScriptBlock {
    $fullPath = Resolve-Path 'c:\Program Files\Internet Explorer\iexplore.exe'
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::OpenRead($fullPath)
    $hash = [System.BitConverter]::ToString($md5.ComputeHash($file))
    $hash -replace "-", ""
    $file.Dispose()
}

其他回答

这个网站有一个例子:使用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()

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

CertUtil -hashfile file.foo MD5

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

这将返回远程计算机上文件的MD5哈希值:

Invoke-Command -ComputerName RemoteComputerName -ScriptBlock {
    $fullPath = Resolve-Path 'c:\Program Files\Internet Explorer\iexplore.exe'
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::OpenRead($fullPath)
    $hash = [System.BitConverter]::ToString($md5.ComputeHash($file))
    $hash -replace "-", ""
    $file.Dispose()
}

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

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

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

Get-ChildItem WTAM*.tar | % {.\fciv $_.Name}
(
    [System.Security.Cryptography.MD5CryptoServiceProvider]::new().ComputeHash(
        [System.Text.UTF8Encoding]::new().GetBytes($yourText)
    ) `
    | %{ [Convert]::ToString($_, 16) }
) -join ''

$yourText = 'hello'输出5d41402abc4b2a76b9719d911017c592