Files
general-scripts-and-system-…/Windows-Scripts/checksum.ps1
T
2026-09-25 15:43:25 -06:00

397 lines
16 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 / --out) - auto generates file based on rules
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
[Alias('o', 'out', 'SaveToFile')]
[switch]$SaveToFile,
# Custom Output file name (-f / --outfile)
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
[Alias('f', 'outfile')]
[string]$OutFile,
# File containing checksums to verify (-c / --check)
[Parameter(Mandatory = $false, ParameterSetName = 'Verify')]
[Alias('c', 'check')]
[string]$Check,
# Direct checksum hash string to match against (-m / --match)
[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 / --recursive)
[Parameter(Mandatory = $false)]
[Alias('r', 'recursive')]
[switch]$Recursive,
# Help flag (-h / --help)
[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 cryptographic hash algorithms (SHA256, SHA512, SHA1, MD5, SHA384).
Outputs hash values in standard GNU coreutils format (<hash> <filename>).
Supports both single-dash (-o, -c, -r) and double-dash (--out, --check, --recursive) GNU-style flags.
Ignores checksum metadata files (.md5, .sha1, .sha256, .sha384, .sha512) during wildcards unless passed explicitly.
PARAMETERS
-FilePath <string[]>
Specifies the target file(s) or wildcard pattern (*).
-o, --out, -SaveToFile <switch>
Enables auto-saving checksum results to file(s).
- If input contains a wildcard (*), writes to 'checksums.<algo>'.
- If an explicit file is given, writes to '<filename>.<algo>'.
When combined with -r and *, recursively auto-generates checksum files per directory.
-f, --outfile, -OutFile <string>
Specifies an explicit destination filename for saving checksum output.
-c, --check, -Check <string>
Reads hashes from a specified checksum file and verifies target files on disk.
If -r is specified, recursively looks for and validates checksum files by name across subdirectories.
-m, --match, -Match <string>
Compares the computed hash of target file(s) directly against a given hash string.
-a, --algo, --algorithm, -Algorithm <string>
Specifies the hash algorithm to use.
Supported options: SHA1, SHA256 (default), SHA384, SHA512, MD5.
In -c or -m mode, auto-detects algorithm from hash length if omitted.
-r, --recursive, -Recursive <switch>
Processes target files or verification files recursively across directory structures.
-h, --help, -Help <switch>
Displays this help documentation.
EXAMPLES
1. Compute SHA256 for a single file:
.\checksum.ps1 myfile.iso
2. Compute SHA512 checksums recursively and auto-save:
.\checksum.ps1 * -r -o -a SHA512
.\checksum.ps1 * --recursive --out --algo SHA512
3. Verify checksums against a verification file:
.\checksum.ps1 -c checksums.sha256
.\checksum.ps1 --check checksums.sha256
4. Recursively verify checksum files across subdirectories:
.\checksum.ps1 --check checksums.sha256 --recursive
5. Compare file directly against an expected hash string:
.\checksum.ps1 myfile.bin --match 406653a68bd3538975656831f33f031b
'@
};
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 {
$helpInPath =$false;
if ($FilePath) {
foreach ($p in ($FilePath)) {
if ($p -match '^(?i)[-/]{1,2}(h\vert{}help\vert{}\?)$') {
$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) {
$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(".\") -or $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;
}
elseif ($line -match '^([a-fA-F0-9]{128}|[a-fA-F0-9]{96}|[a-fA-F0-9]{64}|[a-fA-F0-9]{40}|[a-fA-F0-9]{32})') {
$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; };
$expectedHash =$null;
$targetFile =$null;
# Standard GNU checksum format: <hash> <space/asterisk> <filename>
if ($line -match '^([a-fA-F0-9]+)\s+[* ]?(.*)$') {
$expectedHash =$Matches[1].ToLower();
$targetFile =$Matches[2].Trim().TrimStart('*');
}
# Fallback for unspaced files: <hash><filename>
elseif ($line -match '^([a-fA-F0-9]{128}\vert{}[a-fA-F0-9]{96}\vert{}[a-fA-F0-9]{64}\vert{}[a-fA-F0-9]{40}\vert{}[a-fA-F0-9]{32})[* ]?(.*)$') {
$expectedHash =$Matches[1].ToLower();
$targetFile =$Matches[2].Trim().TrimStart('*');
};
if ($expectedHash -and $targetFile) {$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(".\") -or $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(".\") -or $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';
};
$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);
};
$linesToWrite = @();
foreach ($item in ($filesInDir)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower();
$relativePath =$item.Name;
$outputLine = "${hash}${relativePath}";
$linesToWrite +=$outputLine;
Write-Output $outputLine;
};
Set-Content -Path ($currentOutFile) -Value$linesToWrite -Encoding utf8;
};
}
else {
$singleOutFile =$null;
if ([string]::IsNullOrWhiteSpace($OutFile)) {
if ($isWildcardGlobal) {$singleOutFile = "checksums.$($Algorithm.ToLower())";
}
} else {
$singleOutFile =$OutFile;
};
if ($singleOutFile) {$linesToWrite = @();
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(".\") -or $relativePath.StartsWith("./")) {
$relativePath =$relativePath.Substring(2);
};
$outputLine = "${hash}${relativePath}";
$linesToWrite +=$outputLine;
Write-Output $outputLine;
};
Set-Content -Path ($singleOutFile) -Value$linesToWrite -Encoding utf8;
} 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(".\") -or $relativePath.StartsWith("./")) {
$relativePath =$relativePath.Substring(2);
};
$outputLine = "${hash}${relativePath}";
$currentOutFile = "$($item.FullName).$($Algorithm.ToLower())";
Set-Content -Path ($currentOutFile) -Value$outputLine -Encoding utf8;
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(".\") -or $relativePath.StartsWith("./")) {
$relativePath =$relativePath.Substring(2);
};
$outputLine = "${hash}${relativePath}";
Write-Output $outputLine;
};
};
}
}
end {}