一个计算MD5的脚本
今天在monad的team blog上看到一个脚本,可以获取每个文件的MD5 hash,引用到这里分享一下。
## Calculates the hash of a file and returns it as a string.
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
return [string]$hashByteArray;
}
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
return [string]$hashByteArray;
}
用法:
MSH>"foo" > foo.txt
MSH>"bar" > bar.txt
MSH>"foo" > AlternateFoo.txt
MSH>dir *.txt | foreach { get-md5 $_ }
33 69 151 28 248 32 88 177 8 34 154 58 46 59 255 53
54 122 136 147 125 209 249 229 12 105 236 19 140 5 107 169
33 69 151 28 248 32 88 177 8 34 154 58 46 59 255 53
不管怎么说,MSH确实是一个dot net脚本,直接调用FCL里的方法确实增强了脚本的威力。比起VBscript时代的COM粘贴剂又不可同日而语了。