Created
January 31, 2013 04:32
-
-
Save bradwilson/4680208 to your computer and use it in GitHub Desktop.
Hashing function for PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[string]$pattern = "*.*", | |
[ValidateSet("md5", "sha1", "sha256", "sha384", "sha512")]$algorithm = "sha1", | |
[switch]$recurse | |
) | |
[Reflection.Assembly]::LoadWithPartialName("System.Security") | out-null | |
if ($algorithm -eq "sha1") { | |
$hashimpl = new-Object System.Security.Cryptography.SHA1Managed | |
} | |
elseif ($algorithm -eq "sha256") { | |
$hashimpl = new-Object System.Security.Cryptography.SHA256Managed | |
} | |
elseif ($algorithm -eq "sha384") { | |
$hashimpl = new-Object System.Security.Cryptography.SHA384Managed | |
} | |
elseif ($algorithm -eq "sha512") { | |
$hashimpl = new-Object System.Security.Cryptography.SHA512Managed | |
} | |
elseif ($algorithm -eq "md5") { | |
$hashimpl = new-Object System.Security.Cryptography.MD5CryptoServiceProvider | |
} | |
$pattern | %{ | |
$files = get-childitem -Recurse:$recurse $_ | ?{ $_.PSIsContainer -eq $false } | |
if ($files -ne $null) { | |
$files | %{ | |
$filename = $_.FullName | |
$hash = "" | |
$file = [System.IO.File]::Open($filename, "open", "read") | |
$hashimpl.ComputeHash($file) | %{ | |
$hash = $hash + $_.ToString("x2") | |
} | |
$file.Dispose() | |
$result = new-object PSObject | |
$result | add-member NoteProperty "Path" $filename | |
$result | add-member NoteProperty "Hash" $hash | |
write-output $result | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment