1: #----------------------------------------------------------------
2: # Md5.ps1
3: #----------------------------------------------------------------
4: param
5: (
6: [string]$filespec = $null,
7: [bool]$colons = $false
8: );
9:
10: #----------------------------------------------------------------
11: # function Do-Md5
12: #----------------------------------------------------------------
13: function Do-Md5()
14: {
15: param
16: (
17: [string]$filespec = $null,
18: [bool]$colons = $false
19: );
20:
21: $hashAlgorithm = new-object -TypeName "System.Security.Cryptography.MD5CryptoServiceProvider";
22:
23: $files = @(Get-ChildItem -Path $filespec -ErrorAction SilentlyContinue);
24: foreach ($file in $files)
25: {
26: $stream = $file.OpenRead();
27: $hashByteArray = $hashAlgorithm.ComputeHash($stream);
28: $stream.Close();
29:
30: $md5StringBuilder = New-Object System.Text.StringBuilder
31:
32: $hashByteArray | % {
33: if ( $colons )
34: {
35: if ( $md5StringBuilder.Length -gt 0 ) { [void] $md5StringBuilder.Append(":") }
36: }
37: [void] $md5StringBuilder.Append($_.ToString("x2"))
38: }
39:
40: "MD5($($file.Name))= $($md5StringBuilder.ToString())";
41:
42: # Ensure stream is closed if exceptions occurred.
43: trap
44: {
45: if ($stream -ne $null) { $stream.Close(); }
46: break;
47: }
48: }
49: }
50:
51: Do-Md5 -filespec $filespec -colons $colons;