Powershell 下计算MD5 之二[转]

转载自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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值