您的位置:首页 > 运维架构 > Shell

Powershell 下计算MD5 之二[转]

2009-02-02 13:29 225 查看
转载自http://blogs.msdn.com/powershell/archive/2006/04/25/583225.aspx



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;

}



I think about the only new thing here is the trap statement. It’ll get called if any exception is thrown, otherwise its just ignored. Hopefully nothing will go wrong with the function but if anything does I want to be sure to close any open streams. Anyway, keep this function around, we’ll use it along with AddNotes and group-object to write a simple script that can search directories and tell us all the files that are duplicates. Now… an example of this function in use:



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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: