366 lines
14 KiB
PowerShell
366 lines
14 KiB
PowerShell
[CmdletBinding(DefaultParameterSetName='Generate')]
|
|
param(
|
|
# File(s) or wildcard pattern to compute checksum for
|
|
[Parameter(Position = 0, ParameterSetName = 'Generate', ValueFromPipeline = $true)]
|
|
[Parameter(Position = 0, ParameterSetName = 'Match', ValueFromPipeline = $true)]
|
|
[string[]]$FilePath,
|
|
|
|
# Output file switch (-o) - auto generates file based on rules
|
|
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
|
|
[Alias('o', 'out')]
|
|
[switch]$SaveToFile,
|
|
|
|
# Custom Output file name (-f)
|
|
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
|
|
[Alias('f', 'outfile')]
|
|
[string]$OutFile,
|
|
|
|
# File containing checksums to verify (-c mode)
|
|
[Parameter(Mandatory = $false, ParameterSetName = 'Verify')]
|
|
[Alias('c', 'check')]
|
|
[string]$Check,
|
|
|
|
# Direct checksum hash string to match against (-m mode)
|
|
[Parameter(Mandatory = $true, ParameterSetName = 'Match')]
|
|
[Alias('m', 'match')]
|
|
[string]$Match,
|
|
|
|
# Hashing algorithm to use (Defaults to SHA256)
|
|
[Parameter(Mandatory = $false)]
|
|
[Alias('a', 'algo', 'algorithm')]
|
|
[ValidateSet('SHA1', 'SHA256', 'SHA384', 'SHA512', 'MD5')]
|
|
[string]$Algorithm,
|
|
|
|
# Recursive flag (-r)
|
|
[Parameter(Mandatory = $false)]
|
|
[Alias('r', 'recursive')]
|
|
[switch]$Recursive,
|
|
|
|
# Help flag (-h)
|
|
[Parameter(Mandatory = $false)]
|
|
[Alias('h', 'help')]
|
|
[switch]$Help
|
|
)
|
|
|
|
begin {
|
|
function Show-Help {
|
|
@'
|
|
NAME
|
|
checksum - Compute and verify message digests / file checksums
|
|
|
|
SYNOPSIS
|
|
.\checksum.ps1 [-FilePath] <string[]> [-o] [-OutFile <string>] [-Algorithm <string>] [-r]
|
|
.\checksum.ps1 [-FilePath] <string[]> -Match <string> [-Algorithm <string>] [-r]
|
|
.\checksum.ps1 -Check <string> [-Algorithm <string>] [-r]
|
|
.\checksum.ps1 -Help
|
|
|
|
DESCRIPTION
|
|
Computes or verifies checksums using various cryptographic algorithms.
|
|
Outputs hash values in standard Linux utility format (<hash> <filename>).
|
|
Ignores checksum files (.md5, .sha1, .sha256, .sha384, .sha512) unless explicitly passed.
|
|
|
|
PARAMETERS
|
|
-FilePath <string[]>
|
|
Specifies the path to one or more files to hash. Accepts wildcards (*).
|
|
|
|
-o, -Out, --Out <switch>
|
|
Enables writing checksum results to an auto-named file.
|
|
- If input has a wildcard (*), outputs to 'checksums.<algo>'
|
|
- If no wildcard is used, outputs to '<filename>.<algo>' per file.
|
|
When combined with -r and *, it auto-generates checksum files
|
|
inside the current working directory and each subdirectory recursively.
|
|
|
|
-f, -OutFile, --OutFile <string>
|
|
Specifies an explicit output file name to save results to.
|
|
|
|
-r, -Recursive, --Recursive <switch>
|
|
Recursively generate or verify checksums in subdirectories.
|
|
|
|
-c, -Check, --Check <string>
|
|
Read checksums from the specified file and verify them against files on disk.
|
|
If -r is used, searches for the specified filename recursively in subdirectories.
|
|
|
|
-m, -Match, --Match <string>
|
|
Compare the computed hash of the target file(s) against a specific hash string.
|
|
|
|
-a, -Algorithm, --Algorithm <string>
|
|
Specifies the cryptographic hash algorithm to use.
|
|
Supported values: SHA1, SHA256 (default), SHA384, SHA512, MD5.
|
|
If omitted in -c or -m mode, the algorithm is auto-detected by hash length.
|
|
|
|
-h, -Help, --Help <switch>
|
|
Display this help message.
|
|
|
|
EXAMPLES
|
|
1. Compute SHA256 checksum for a single file:
|
|
.\checksum.ps1 myfile.iso
|
|
|
|
2. Compute checksums for all files and auto-write to files (-o flag):
|
|
.\checksum.ps1 * -r -o
|
|
|
|
3. Verify checksums from verification files recursively:
|
|
.\checksum.ps1 -c checksums.sha256 -r
|
|
'@
|
|
}
|
|
|
|
function Get-AlgorithmFromHashLength {
|
|
param([string]$HashString)
|
|
|
|
switch ($HashString.Trim().Length) {
|
|
32 { return 'MD5' }
|
|
40 { return 'SHA1' }
|
|
64 { return 'SHA256' }
|
|
96 { return 'SHA384' }
|
|
128 { return 'SHA512' }
|
|
default {
|
|
Write-Error "checksum: Could not auto-detect algorithm for hash length $($HashString.Length). Please specify -Algorithm."
|
|
return $null
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
process {
|
|
# Bulletproof help check (catches --help passed positionally)
|
|
$helpInPath =$false
|
|
if ($FilePath) {
|
|
foreach ($p in ($FilePath)) {
|
|
if ($p -match '^(?i)[-/]{1,2}(h\vert{}help)$') {
|
|
$helpInPath =$true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($Help.IsPresent -or$helpInPath) {
|
|
Show-Help
|
|
return
|
|
}
|
|
|
|
if (-not [string]::IsNullOrWhiteSpace($Algorithm)) {
|
|
$Algorithm =$Algorithm.ToUpper()
|
|
}
|
|
|
|
# --- ITEM GATHERING (Generate & Match Modes) ---
|
|
if ($PSCmdlet.ParameterSetName -in @('Generate', 'Match')) {
|
|
if (-not $FilePath -or$FilePath.Count -eq 0) {
|
|
Write-Error "checksum: Missing file path parameter. Use -Help for usage."
|
|
return
|
|
}
|
|
|
|
$allItems = @();
|
|
$isWildcardGlobal =$false;
|
|
$skipExtensions = @('.md5', '.sha1', '.sha256', '.sha384', '.sha512');
|
|
|
|
foreach ($pathEntry in ($FilePath)) {
|
|
$isWildcard = ($pathEntry -match '\*');
|
|
if ($isWildcard) { $isWildcardGlobal =$true }
|
|
|
|
$resolvedItems = @();
|
|
if ($Recursive) {
|
|
# Parens around variables prevent space-stripping crashes
|
|
$resolvedItems = Get-ChildItem -Path ($pathEntry) -Recurse -File -ErrorAction 'SilentlyContinue'
|
|
} else {
|
|
if ($isWildcard -or ($pathEntry -match '\?')) {
|
|
$resolvedItems = Get-ChildItem -Path ($pathEntry) -File -ErrorAction 'SilentlyContinue'
|
|
} else {
|
|
$resolvedItems = Get-Item -Path ($pathEntry) -ErrorAction 'SilentlyContinue'
|
|
}
|
|
}
|
|
|
|
if (-not $resolvedItems) {
|
|
Write-Error "checksum: $($pathEntry)`: No such file or directory"
|
|
continue
|
|
}
|
|
|
|
$explicitFileFound = $false;
|
|
if ((-not $isWildcard) -and (Test-Path -Path ($pathEntry) -PathType 'Leaf')) {
|
|
$explicitFileFound = $true
|
|
}
|
|
|
|
foreach ($item in ($resolvedItems)) {
|
|
if ($item.PSIsContainer) { continue }
|
|
|
|
if (-not $explicitFileFound) {
|
|
if ($skipExtensions -contains $item.Extension.ToLower()) {
|
|
continue
|
|
}
|
|
}
|
|
$allItems += $item
|
|
}
|
|
}
|
|
}
|
|
|
|
# --- DIRECT MATCH MODE (-m / -Match) ---
|
|
if ($PSCmdlet.ParameterSetName -eq 'Match') {
|
|
if ([string]::IsNullOrWhiteSpace($Algorithm)) {
|
|
$Algorithm = Get-AlgorithmFromHashLength -HashString ($Match)
|
|
if (-not $Algorithm) { return }
|
|
}
|
|
|
|
$expectedHash = $Match.Trim().ToLower();
|
|
|
|
foreach ($item in ($allItems)) {
|
|
$actualHash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
|
|
$targetFile = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue'
|
|
if (-not $targetFile) { $targetFile = $item.Name }
|
|
if ($targetFile.StartsWith(".\")) { $targetFile = $targetFile.Substring(2) }
|
|
|
|
if ($actualHash -eq $expectedHash) {
|
|
Write-Host "${targetFile}: " -NoNewline
|
|
Write-Host "OK" -ForegroundColor Green
|
|
} else {
|
|
Write-Host "${targetFile}: " -NoNewline
|
|
Write-Host "FAILED" -ForegroundColor Red
|
|
}
|
|
}
|
|
}
|
|
# --- VERIFICATION MODE (-c / -Check) ---
|
|
elseif ($PSCmdlet.ParameterSetName -eq 'Verify') {
|
|
$checkFiles = @();
|
|
if ($Recursive) {
|
|
$checkFileName = Split-Path -Path ($Check) -Leaf
|
|
$checkFiles = Get-ChildItem -Path '.\' -Filter ($checkFileName) -Recurse -File -ErrorAction 'SilentlyContinue'
|
|
} else {
|
|
if (Test-Path -Path ($Check) -PathType 'Leaf') {
|
|
$checkFiles = @(Get-Item -Path ($Check))
|
|
}
|
|
}
|
|
|
|
if (-not $checkFiles -or $checkFiles.Count -eq 0) {
|
|
Write-Error "checksum: $($Check)`: No such file or directory"
|
|
return
|
|
}
|
|
|
|
foreach ($cf in ($checkFiles)) {
|
|
$lines = Get-Content -Path ($cf.FullName)
|
|
$baseDir =$cf.DirectoryName
|
|
|
|
$fileAlgo =$Algorithm
|
|
if ([string]::IsNullOrWhiteSpace($fileAlgo)) {
|
|
foreach ($line in ($lines)) {
|
|
if ([string]::IsNullOrWhiteSpace($line) -or$line.StartsWith("#")) { continue }
|
|
if ($line -match '^([a-fA-F0-9]+)\s+') {
|
|
$fileAlgo = Get-AlgorithmFromHashLength -HashString ($Matches[1])
|
|
break
|
|
}
|
|
}
|
|
if ([string]::IsNullOrWhiteSpace($fileAlgo)) {$fileAlgo = 'SHA256' }
|
|
}
|
|
|
|
foreach ($line in ($lines)) {
|
|
if ([string]::IsNullOrWhiteSpace($line) -or$line.StartsWith("#")) { continue }
|
|
|
|
if ($line -match '^([a-fA-F0-9]+)\s+[* ]?(.*)$') {$expectedHash = $Matches[1].ToLower()$targetFile = $Matches[2].Trim().TrimStart('*')$targetFullPath = Join-Path -Path ($baseDir) -ChildPath ($targetFile)
|
|
|
|
if (Test-Path -Path ($targetFullPath) -PathType 'Leaf') {$actualHash = (Get-FileHash -Path ($targetFullPath) -Algorithm ($fileAlgo)).Hash.ToLower()
|
|
|
|
$displayPath = Resolve-Path -Path ($targetFullPath) -Relative -ErrorAction 'SilentlyContinue'
|
|
if (-not $displayPath) { $displayPath =$targetFile }
|
|
if ($displayPath.StartsWith(".\")) { $displayPath =$displayPath.Substring(2) }
|
|
|
|
if ($actualHash -eq$expectedHash) {
|
|
Write-Host "${displayPath}: " -NoNewline
|
|
Write-Host "OK" -ForegroundColor Green
|
|
} else {
|
|
Write-Host "${displayPath}: " -NoNewline
|
|
Write-Host "FAILED" -ForegroundColor Red
|
|
}
|
|
} else {
|
|
$displayPath =$targetFile
|
|
if ($baseDir -ne (Get-Location).Path) {$displayPath = Join-Path -Path (Resolve-Path -Path ($baseDir) -Relative -ErrorAction 'SilentlyContinue') -ChildPath ($targetFile)
|
|
if ($displayPath.StartsWith(".\")) { $displayPath =$displayPath.Substring(2) }
|
|
}
|
|
Write-Host "${displayPath}: " -NoNewline
|
|
Write-Host "FAILED open or read" -ForegroundColor Red
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
# --- GENERATION MODE ---
|
|
else {
|
|
if ([string]::IsNullOrWhiteSpace($Algorithm)) {$Algorithm = 'SHA256'
|
|
}
|
|
|
|
# Enable output if the switch is used OR an explicit file is provided
|
|
$wantOutFile = $SaveToFile.IsPresent -or (-not [string]::IsNullOrWhiteSpace($OutFile));
|
|
|
|
if ($wantOutFile) {
|
|
if ($Recursive -and$isWildcardGlobal) {
|
|
$groupedItems =$allItems | Group-Object DirectoryName
|
|
|
|
foreach ($group in ($groupedItems)) {
|
|
$dirPath =$group.Name
|
|
$filesInDir =$group.Group
|
|
|
|
if ([string]::IsNullOrWhiteSpace($OutFile)) {
|
|
$currentOutFile = Join-Path -Path ($dirPath) -ChildPath "checksums.$($Algorithm.ToLower())"
|
|
} else {
|
|
$currentOutFile = Join-Path -Path ($dirPath) -ChildPath ($OutFile)
|
|
}
|
|
|
|
$null = New-Item -Path ($currentOutFile) -ItemType 'File' -Force
|
|
|
|
foreach ($item in ($filesInDir)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
|
|
$relativePath =$item.Name
|
|
|
|
$outputLine = "$hash$relativePath"
|
|
Add-Content -Path ($currentOutFile) -Value ($outputLine)
|
|
Write-Output $outputLine
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
$singleOutFile =$null;
|
|
|
|
if ([string]::IsNullOrWhiteSpace($OutFile)) {
|
|
if ($isWildcardGlobal) {$singleOutFile = "checksums.$($Algorithm.ToLower())"
|
|
}
|
|
} else {
|
|
$singleOutFile =$OutFile
|
|
}
|
|
|
|
if ($singleOutFile) {
|
|
$null = New-Item -Path ($singleOutFile) -ItemType 'File' -Force
|
|
}
|
|
|
|
foreach ($item in ($allItems)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
|
|
|
|
$relativePath = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue'
|
|
if (-not $relativePath) { $relativePath =$item.Name }
|
|
if ($relativePath.StartsWith(".\")) {
|
|
$relativePath =$relativePath.Substring(2)
|
|
}
|
|
|
|
$outputLine = "$hash$relativePath"
|
|
|
|
if ($singleOutFile) {
|
|
Add-Content -Path ($singleOutFile) -Value ($outputLine)
|
|
} else {
|
|
$currentOutFile = "$($item.FullName).$($Algorithm.ToLower())"
|
|
$null = New-Item -Path ($currentOutFile) -ItemType 'File' -Force
|
|
Add-Content -Path ($currentOutFile) -Value ($outputLine)
|
|
}
|
|
|
|
Write-Output $outputLine
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
foreach ($item in ($allItems)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
|
|
|
|
$relativePath = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue'
|
|
if (-not $relativePath) { $relativePath =$item.Name }
|
|
if ($relativePath.StartsWith(".\")) {
|
|
$relativePath =$relativePath.Substring(2)
|
|
}
|
|
|
|
$outputLine = "$hash$relativePath"
|
|
Write-Output $outputLine
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
end {} |