-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompare-FileHash.ps1
More file actions
102 lines (86 loc) · 2.15 KB
/
Compare-FileHash.ps1
File metadata and controls
102 lines (86 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<#
.SYNOPSIS
Compare the hash of a file against an expected value.
.DESCRIPTION
Useful for verifying downloads (e.g. Kali Linux images).
Supports SHA256, SHA1, and MD5.
.EXAMPLE
\.Compare-FileHash.ps1 -FilePath "kali-linux.7z" -ExpectedHash "abc123..."
#>
param(
[Parameter(Mandatory)]
[string]$FilePath,
[Parameter(Mandatory)]
[string]$ExpectedHash,
[ValidateSet("SHA256", "SHA1", "MD5")]
[string]$Algorithm = "SHA256"
)
function Test-FileExists {
param([string]$Path)
if (-not (Test-Path -Path $Path -PathType Leaf)) {
throw "File not found: $Path"
}
}
function Test-ExpectedHash {
param(
[string]$Hash,
[string]$Algorithm
)
$lengths = @{
"SHA256" = 64
"SHA1" = 40
"MD5" = 32
}
$Hash = $Hash.Trim().ToLowerInvariant()
if ($Hash.Length -ne $lengths[$Algorithm] -or -not ($Hash -match '^[0-9a-f]+$')) {
throw "ExpectedHash must be $($lengths[$Algorithm]) hex characters for $Algorithm."
}
return $Hash
}
function Main {
param(
[string]$FilePath,
[string]$ExpectedHash,
[string]$Algorithm
)
try {
Test-FileExists -path $FilePath;
$ExpectedHash = Test-ExpectedHash -Hash $ExpectedHash -Algorithm $Algorithm
$actual = (Get-FileHash -Path $FilePath -Algorithm $Algorithm -ErrorAction Stop).Hash.toLower()
if ($actual -eq $ExpectedHash) {
return [PSCustomObject]@{
Success = $true
Expected = $ExpectedHash
Actual = $actual
Algorithm = $Algorithm
FilePath = $FilePath
}
}
return [PSCustomObject]@{
Success = $false
Expected = $ExpectedHash
Actual = $actual
Algorithm = $Algorithm
FilePath = $FilePath
};
} catch {
throw "Failed to compute hash: $_"
}
}
try {
if ($MyInvocation.InvocationName -ne '.') {
$result = Main @PSBoundParameters
if ($result.Success) {
Write-Output "✅ Hash matched!"
exit 0
} else {
Write-Output "❌ Hash mismatch"
Write-Output "Expected: $($result.Expected)"
Write-Output "Actual: $($result.Actual)"
exit 1
}
}
} catch {
Write-Error $_
exit 2
}