Skip to content

Commit 8a0c20b

Browse files
committed
Adds Get-FileHash for PowerShell < 4
1 parent fbab9e2 commit 8a0c20b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: GetFileHash.ps1

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Get-FileHash has been introduced only in PowerShell 4.0
2+
# Here's a compatible implementation for previous versions (SHA1 only for now)
3+
function Get-FileHash {
4+
[CmdletBinding()]
5+
param
6+
(
7+
[parameter(Mandatory=$true)]
8+
[string]$Path,
9+
10+
[string]$Algorithm = "SHA1"
11+
)
12+
process
13+
{
14+
if ($Algorithm -ne "SHA1") {
15+
throw "Unsupported algorithm: $Algorithm"
16+
}
17+
18+
$fullPath = Resolve-Path $Path
19+
$f = [System.IO.File]::OpenRead($fullPath)
20+
$sham = $null
21+
try {
22+
$sham = new-object System.Security.Cryptography.SHA1Managed
23+
$hash = $sham.ComputeHash($f)
24+
25+
$hashSB = new-object System.Text.StringBuilder -ArgumentList ($hash.Length * 2)
26+
foreach ($b in $hash) {
27+
$sb = $hashSB.AppendFormat("{0:x2}", $b)
28+
}
29+
30+
return [pscustomobject]@{Algorithm="SHA1"; Path=$fullPath; Hash=$hashSB.ToString()}
31+
}
32+
finally {
33+
$f.Close()
34+
if($sham) { $sham.Dispose() }
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)