如何使用MD4、MD5、SHA1等常用散列算法对字符串、字节数组、io流等数据进行散列处理……我正在写一个脚本,使驱动器备份,并防止不必要的副本,并检测如果文件被损坏,它需要用一些散列算法,如MD4快速散列文件。如果有人知道如何散列文件,io流,字节数组,字符串...使用任何散列算法,请让我知道。另外,Get-FileHash cmdlet并不是在我遇到的所有Windows安装中都存在。
发布于 2020-05-01 20:23:46
创建一个[System.Security.Cryptography.MD5]实例,然后将文件流传递给它的ComputeHash()方法:
function Get-MD5Sum
{
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[Alias('PSPath')]
[string[]]$Path
)
begin {
$md5 = [System.Security.Cryptography.MD5]::Create()
}
process {
foreach($filePath in $Path){
# Resolve filesystem item
$file = Get-Item -LiteralPath $Path
# Skip if not a file
if($file -isnot [System.IO.FileInfo]){
continue
}
# Open a stream to read the file
$filestream = $file.OpenRead()
try {
# Calculate + format hash, then output
Write-Output $([pscustomobject]@{
File = $file.FullName
Hash = [BitConverter]::ToString($MD5.ComputeHash($filestream)) -replace '-'
})
}
finally {
# close file stream handle
$filestream.Dispose()
}
}
}
end {
# Dispose of the hash provider
$MD5.Dispose()
}
}现在您可以在不使用Get-FileHash的情况下计算MD5文件哈希
PS C:\> $fileHashes = Get-ChildItem . |Get-MD5Sumhttps://stackoverflow.com/questions/61542205
复制相似问题