Skip to content

Instantly share code, notes, and snippets.

@bradwilson
Created January 31, 2013 04:32
Show Gist options
  • Save bradwilson/4680208 to your computer and use it in GitHub Desktop.
Save bradwilson/4680208 to your computer and use it in GitHub Desktop.
Hashing function for PowerShell
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