在MD5 Powershell中获取哈希值

时间:2017-06-01 20:04:02

标签: powershell hash

我正在尝试创建一个脚本,可以获取我使用函数ChildItem获得的文件和目录的哈希MD5。我的剧本目前如下。为什么Hash的一部分不起作用?

 $UserInput = Read-Host



 Get-ChildItem -Path $UserInput -Recurse  


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

2 个答案:

答案 0 :(得分:1)

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

编辑:您的代码应该可以正常工作,甚至比我建议的更好,因为我的示例仅限于文件< 2GB大小。由于你的使用Stream,它更有效(不会先将它全部加载到内存中),并且没有大小限制。

您的文件路径必须是文件,因为您正在进行特定于文件的I / O调用...

答案 1 :(得分:1)

作为一个单行:

Get-ChildItem -Path C:\Temp -Recurse -File | Get-Filehash -Algorithm MD5