8 Commits

Author SHA1 Message Date
PrincessPi 4e798818d1 CHECKSUM GREATLY IMPROVED 2026-09-25 17:02:59 -06:00
PrincessPi 56b08f32da waypoit debuguing 2026-09-25 16:52:30 -06:00
PrincessPi 251c9aa06c waypoit debuguing 2026-09-25 16:51:04 -06:00
PrincessPi 1dbd1ad79b waypoit debuguing 2026-09-25 16:50:16 -06:00
PrincessPi 7bd65e7d76 waypoit debuguing 2026-09-25 16:45:30 -06:00
PrincessPi 2fd8238a98 waypoit debuguing 2026-09-25 16:33:58 -06:00
PrincessPi 503e947eaf waypoit debuguing 2026-09-25 16:20:22 -06:00
PrincessPi 07a29167dd waypoit debuguing 2026-09-25 16:19:14 -06:00
2 changed files with 540 additions and 289 deletions
+2
View File
@@ -0,0 +1,2 @@
1. recursive verify error: `FAILED open or read`
2. recursive progress set to count total number of files recursively first for progress bar
+538 -289
View File
@@ -1,19 +1,31 @@
<#
.SYNOPSIS
Princess Pi's Magical CHECKSUM! - Computes and verifies message digests / file checksums.
.DESCRIPTION
Computes or verifies checksums using cryptographic hash algorithms (SHA256, SHA512, SHA1, MD5, SHA384).
Supports parallel processing, recursive scanning, direct hash matching, and verification file parsing.
.NOTES
Requires PowerShell 7.0 or higher.
#>
[CmdletBinding(DefaultParameterSetName='Generate')] [CmdletBinding(DefaultParameterSetName='Generate')]
param( param(
# File(s) or wildcard pattern to compute checksum for # File(s) or wildcard pattern to compute checksum for
[Parameter(Position = 0, ParameterSetName = 'Generate', ValueFromPipeline = $true)] [Parameter(Position = 0, ParameterSetName = 'Generate', ValueFromPipeline = $true)]
[Parameter(Position = 0, ParameterSetName = 'Match', ValueFromPipeline = $true)] [Parameter(Position = 0, ParameterSetName = 'Match', ValueFromPipeline = $true)]
[Parameter(Position = 0, ParameterSetName = 'PrincessPi', ValueFromPipeline = $false)]
[Alias('i', 'input', 'if', 'InputFile')]
[string[]]$FilePath, [string[]]$FilePath,
# Custom output file (-f / -OutFile) # Custom output file (-f / -OutFile / -of)
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')] [Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
[Alias('f')] [Alias('f', 'of')]
[string]$OutFile, [string]$OutFile,
# Auto output file switch (-o) # Auto output file switch (-s / -Save / -o)
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')] [Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
[Alias('o')] [Alias('s', 'o')]
[switch]$AutoOut, [switch]$Save,
# File containing checksums to verify (-c / -Check) # File containing checksums to verify (-c / -Check)
[Parameter(Mandatory = $false, ParameterSetName = 'Verify')] [Parameter(Mandatory = $false, ParameterSetName = 'Verify')]
@@ -36,22 +48,37 @@ param(
[Alias('r')] [Alias('r')]
[switch]$Recursive, [switch]$Recursive,
# Princess Pi art flag (-pp / -PrincessPi)
[Parameter(Mandatory = $true, ParameterSetName = 'PrincessPi')]
[Alias('pp')]
[switch]$PrincessPi,
# Help flag (-h / -Help) # Help flag (-h / -Help)
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[Alias('h')] [Alias('h')]
[switch]$Help [switch]$Help
) )
begin { # --- ENVIRONMENT SANITY CHECK ---
function Show-Help { if ($PSVersionTable.PSVersion.Major -lt 7) {
@' Write-Error "checksum: This script requires PowerShell 7 or higher for parallel execution (-Parallel support). Current version is $($PSVersionTable.PSVersion)."
exit 1
}
# --- HELPER FUNCTIONS ---
function Show-Help {
@'
Princess Pi's Magical CHECKSUM!
NAME NAME
checksum - Compute and verify message digests / file checksums checksum - Compute and verify message digests / file checksums
SYNOPSIS SYNOPSIS
.\checksum.ps1 [-FilePath] <string[]> [-o] [-f <string>] [-Algorithm <string>] [-r] .\checksum.ps1 [-FilePath] <string[]> [-s] [-f <string>] [-Algorithm <string>] [-r]
.\checksum.ps1 [-FilePath] <string[]> -Match <string> [-Algorithm <string>] [-r] .\checksum.ps1 [-FilePath] <string[]> -Match <string> [-Algorithm <string>] [-r]
.\checksum.ps1 -Check <string> [-Algorithm <string>] [-r] .\checksum.ps1 -Check <string> [-Algorithm <string>] [-r]
.\checksum.ps1 -PrincessPi
.\checksum.ps1 -Help .\checksum.ps1 -Help
DESCRIPTION DESCRIPTION
@@ -60,18 +87,18 @@ DESCRIPTION
Ignores checksum metadata files (.md5, .sha1, .sha256, .sha384, .sha512) during wildcards unless passed explicitly. Ignores checksum metadata files (.md5, .sha1, .sha256, .sha384, .sha512) during wildcards unless passed explicitly.
PARAMETERS PARAMETERS
-FilePath <string[]> -FilePath, -i, -input, -if, -InputFile <string[]>
Specifies the target file(s) or wildcard pattern (*). Specifies the target file(s) or wildcard pattern (*).
-o, -O -s, -S, -Save, -o, -O <switch>
Auto-saves checksum results. (Takes no arguments). Auto-saves checksum results. (Takes no arguments).
- If input filename contains a wildcard (*), saves to 'checksums.<algo>'. - If input filename contains a wildcard (*), saves to 'checksums.<algo>'.
- If input filename does NOT contain a wildcard, saves to '<filename>.<algo>'. - If input filename does NOT contain a wildcard, saves to '<filename>.<algo>'.
When combined with -r and *, recursively auto-generates checksums per directory. When combined with -r and *, recursively auto-generates checksums per directory.
-f, -F, -OutFile <string> -f, -F, -of, -OF, -OutFile <string>
Saves checksum results to a specific custom filename. Saves checksum results to a specific custom filename.
Overrides the auto-naming behavior of -o if both are passed. Overrides the auto-naming behavior of -s if both are passed.
-c, -C, -Check <string> -c, -C, -Check <string>
Reads hashes from a specified checksum file and verifies target files on disk. Reads hashes from a specified checksum file and verifies target files on disk.
@@ -88,15 +115,19 @@ PARAMETERS
-r, -R, -Recursive <switch> -r, -R, -Recursive <switch>
Processes target files or verification files recursively across directory structures. Processes target files or verification files recursively across directory structures.
-pp, -PP, -PrincessPi <switch>
Displays Princess Pi!
-h, -H, -Help <switch> -h, -H, -Help <switch>
Displays this help documentation. Displays this help documentation.
Also displays on any error.
EXAMPLES EXAMPLES
1. Compute SHA256 for a single file and auto-save as 'myfile.iso.sha256': 1. Compute SHA256 for a single file and auto-save as 'myfile.iso.sha256':
.\checksum.ps1 myfile.iso -o .\checksum.ps1 myfile.iso -s
2. Compute SHA512 recursively and auto-save as 'checksums.sha512' in each folder: 2. Compute SHA512 recursively and auto-save as 'checksums.sha512' in each folder:
.\checksum.ps1 * -r -o -a SHA512 .\checksum.ps1 * -r -s -a SHA512
3. Compute SHA256 checksums and save to a specific custom file: 3. Compute SHA256 checksums and save to a specific custom file:
.\checksum.ps1 * -f my_hashes.txt .\checksum.ps1 * -f my_hashes.txt
@@ -106,302 +137,520 @@ EXAMPLES
5. Compare file directly against an expected hash string: 5. Compare file directly against an expected hash string:
.\checksum.ps1 myfile.bin -m 406653a68bd3538975656831f33f031b .\checksum.ps1 myfile.bin -m 406653a68bd3538975656831f33f031b
Princess Pi LOVES YOU!~
https://linktr.ee/princesspi3
'@ '@
};
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 { function Write-ErrorWithHelp {
$helpInPath = $false; param([string]$ErrorMessage);
if ($FilePath) { Show-Help;
foreach ($p in ($FilePath)) { Write-Host "";
if ($p -match '^(?i)[-/]{1,2}(h|help|\?)$') { Write-Error $ErrorMessage;
$helpInPath = $true; }
break;
}
};
};
if ($Help.IsPresent -or $helpInPath) { function Show-PrincessPiArt {
Show-Help; $art = @'
=#= -- ##*+++++ *+
-#=#- +# -*%%= ##++++++++++# ##*********#
#==#= *** %%++%% -++# #++++++++++++*+ *#***************#
#===#= %***+%++#*%%@+++++% #++++++++++++**+++#******++********#
====+#%@*******###%=%++##++% #+++++++++++*++++++++#***====+****++#
=#=*==**#*#########%++#*+++@ *++++++++#+++++++++++#****==+******#
*#=====%####***%%++++#*+++**% ++++++++*+++++++++++++#************#*******
@****#==%####**#*+++++++#+++#**# #+++++++++++++++++++#####+*****************#
@****#######%**@+*%**#%+++++%##*** #+++++++++++++++++#+++++#****+======*****+
#****##%####@**%+*******@@+++@###**% #+++++++++++++*++++++++++****========****#
****#####%%*%*%+***@@@%%@*+++@####** *+++++++++++++++++++++#****=======****#
%***####%%**+%%*++*@=##@@%@++++%###*** ++++*+++++++++++#+**************#
@%%%@@##%%#++++++++==**@@**+++%*###**% +++++++++++#*+++++#*********####
%###%++++++++====**#++++%**##**% @% ++++#+++++++++++++**************#
%###%++++++++++++++++++%**%##**%@###@ %++++++++++++++++***=====********
###%%++++++++%++++++*%%%%###***##%##@ +++++++++++++##**************#
###%%%%+++++##+++++++#*+%###***%%%##@ ++++++++++++++%********+############%@
@%%*@*%%%%###****+*%%****++%##***%##@@@ #+++++++++++++++*********###*****#########*
#%%###***#####%**++++##**%#@@#@ ##+++++++++*###%#+***+***##*************#######
@#%%####%%####%+++++++##*######%++++++++++++++#*+++++#%###%#######*********######%
##%########@%@+++@###%*%#####@+++++++++++%**++++++++++%%%%%%########***==**###%##%
%#%###%###########@@%#%#@@##++++++++****++++********+++ %########**===*###%*#
#**##%####@@####%@######%*++++++++++++++++#++**+*#++++# ########******###% %
@#***# ###%@@##%#######@+++++++++++++++++++++%*++**++++# *########******##% @
*******% %##% =@#########++++++++++++++++++#++++*%++*#%#++# ########******##%
#@%@# %% *@#@@###*+++++++++++++++++++%+++##+++###++* ##*#####******##@
**##%*++%++++++++++++++++++++++++++++++++% +#**#####******###
##%#######*@***+#+++++++++++++++#***#++++++++++++ %**#####*******#%
*+++++$****##****++++++++##% #******#+++++++++++ %**#####*******#@
#++++++++*******- ++++++++# *******#++++++++++# @**#####*******#
#@@+++++++******- *+++++++# #******#+++++++++* **####%**==+**@
@@@@@+++ %+++++++# ******# %+++++++ %*###%***===**@ %=
@@@@@@@@@ #+++++++# =****** #++++++% *###%#***=+**% %**
@@@@@@@@@@ ++++++++# ******# #++++++# *##@%********% @*@
@@+@@@++@@+ ++++++++# ******# #++++++# @## #*********@ #***#
@@+@@++@@@++ @@@++++++* @@@%**** #@@++++% +## %#****************%
@*@**@+++# @@@@+++++ @@@@@@**# @@@@@++++# @# %#****************
+#+++++# @@@@@@+++% @@@@@@@@# @@@@@@@++ @ %##************%
#+++** @@@@@@@@@@ @@@@@@@@@ @@@@@@@@@ %###********%*
@@@@@@@@@@+ @@@@@@@@@@ =@@@@@@@@@ %%#####%%
*@@@@@@@@@@ @+*@@@@@@@= @@++@@@@@@
@++@@@@@@@@ #**@**@@@@@ *@@*#@@@@@@ -=
@%#@@@@@@@@ *#***@@@@@@ @+#+@++#@@@
#+++@++@@@@@ **********# #+++++@+@@@@
##+#+++@@@@@@ ##****#### *+#+##+++@@%%
#+++++++++++# #++++++++++#
#########*
____ ____ ____ _ _ ___ ____ ___ ___ ____ ____
( _ \( _ \(_ _)( \( )/ __)( ___)/ __)/ __) ( _ \(_ _)/\/
)___/ ) / _)(_ ) (( (__ )__) \__ \\__ \ )___/ _)(_
(__) (_)\_)(____)(_)\_)\___)(____)(___/(___/ (__) (____)
Princess Pi
https://linktr.ee/princesspi3
'@
Write-Host $art -ForegroundColor Blue;
}
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-ErrorWithHelp "checksum: Could not auto-detect algorithm for hash length $($HashString.Length). Please specify -Algorithm.";
return $null;
}
}
}
# --- MAIN EXECUTION FLOW ---
$helpInPath = $false;
if ($FilePath) {
foreach ($p in ($FilePath)) {
if ($p -match '^(?i)[-/]{1,2}(h|help|\?)$') {
$helpInPath = $true;
break;
}
}
}
if ($Help.IsPresent -or $helpInPath) {
Show-Help;
return;
}
if ($PrincessPi.IsPresent) {
Show-PrincessPiArt;
return;
}
if (-not [string]::IsNullOrWhiteSpace($Algorithm)) {
$Algorithm = $Algorithm.ToUpper();
}
$isWildcardGlobal = $false;
if ($FilePath) {
foreach ($p in $FilePath) {
if ($p -match '\*') { $isWildcardGlobal = $true; }
}
}
$showProgress = $Recursive.IsPresent -or $isWildcardGlobal -or ($PSCmdlet.ParameterSetName -eq 'Verify');
# --- ITEM GATHERING (Generate & Match Modes) ---
if ($PSCmdlet.ParameterSetName -in @('Generate', 'Match')) {
if (-not $FilePath -or $FilePath.Count -eq 0) {
Write-ErrorWithHelp "checksum: Missing file path parameter. Use -Help for usage.";
return; return;
}; }
if (-not [string]::IsNullOrWhiteSpace($Algorithm)) { $allItems = @();
$Algorithm = $Algorithm.ToUpper(); $skipExtensions = @('.md5', '.sha1', '.sha256', '.sha384', '.sha512');
};
# --- ITEM GATHERING (Generate & Match Modes) --- foreach ($pathEntry in ($FilePath)) {
if ($PSCmdlet.ParameterSetName -in @('Generate', 'Match')) { $isWildcard = ($pathEntry -match '\*');
if (-not $FilePath -or $FilePath.Count -eq 0) { $resolvedItems = @();
Write-Error "checksum: Missing file path parameter. Use -Help for usage.";
return; if ($Recursive) {
}; $resolvedItems = Get-ChildItem -Path ($pathEntry) -Recurse -File -ErrorAction 'SilentlyContinue';
} else {
$allItems = @(); if ($isWildcard -or ($pathEntry -match '\?')) {
$isWildcardGlobal = $false; $resolvedItems = Get-ChildItem -Path ($pathEntry) -File -ErrorAction 'SilentlyContinue';
$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 { } else {
if ($isWildcard -or ($pathEntry -match '\?')) { $resolvedItems = Get-Item -Path ($pathEntry) -ErrorAction 'SilentlyContinue';
$resolvedItems = Get-ChildItem -Path ($pathEntry) -File -ErrorAction 'SilentlyContinue'; }
} else { }
$resolvedItems = Get-Item -Path ($pathEntry) -ErrorAction 'SilentlyContinue';
if (-not $resolvedItems) {
Write-ErrorWithHelp "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;
}
}
}
if (-not $resolvedItems) { # --- DIRECT MATCH MODE (-m / -Match) ---
Write-Error "checksum: $($pathEntry): No such file or directory"; if ($PSCmdlet.ParameterSetName -eq 'Match') {
continue; if ([string]::IsNullOrWhiteSpace($Algorithm)) {
}; $Algorithm = Get-AlgorithmFromHashLength -HashString ($Match);
if (-not $Algorithm) { return; }
}
$explicitFileFound = $false; $expectedHash = $Match.Trim().ToLower();
if ((-not $isWildcard) -and (Test-Path -Path ($pathEntry) -PathType 'Leaf')) { $totalFiles = $allItems.Count;
$explicitFileFound = $true; $currentIndex = 0;
};
foreach ($item in ($resolvedItems)) { $allItems | ForEach-Object -Parallel {
if ($item.PSIsContainer) { continue; }; $item = $_
$algo = $using:Algorithm
$exp = $using:expectedHash
$actualHash = (Get-FileHash -Path ($item.FullName) -Algorithm ($algo)).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); }
[PSCustomObject]@{
TargetFile = $targetFile
IsMatch = ($actualHash -eq $exp)
}
} -ThrottleLimit 16 | ForEach-Object {
$currentIndex++
if ($showProgress -and $totalFiles -gt 0) {
Write-Progress -Activity "Matching Checksums ($Algorithm)" -Status "Processing file $currentIndex of $totalFiles" -PercentComplete (($currentIndex / $totalFiles) * 100);
}
if ($_.IsMatch) {
Write-Host "$($_.TargetFile): " -NoNewline;
Write-Host "OK" -ForegroundColor Green;
} else {
Write-Host "$($_.TargetFile): " -NoNewline;
Write-Host "FAILED" -ForegroundColor Red;
}
}
if ($showProgress) {
Write-Progress -Activity "Matching Checksums ($Algorithm)" -Completed;
}
}
# --- 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-ErrorWithHelp "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 (-not $explicitFileFound) { if ($line -match '^([a-fA-F0-9]+)\s+') {
if ($skipExtensions -contains $item.Extension.ToLower()) { $fileAlgo = Get-AlgorithmFromHashLength -HashString ($Matches[1]);
continue; 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'; }
}
$verifyItems = @();
foreach ($line in ($lines)) {
if ([string]::IsNullOrWhiteSpace($line) -or $line.StartsWith("#")) { continue; }
$expectedHash = $null;
$targetFile = $null;
if ($line -match '^([a-fA-F0-9]+)\s+[* ]?(.*)$') {
$expectedHash = $Matches[1].ToLower();
$targetFile = $Matches[2].Trim().TrimStart('*');
}
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})[* ]?(.*)$') {
$expectedHash = $Matches[1].ToLower();
$targetFile = $Matches[2].Trim().TrimStart('*');
}
if ($expectedHash -and $targetFile) {
$targetFullPath = Join-Path -Path ($baseDir) -ChildPath ($targetFile);
$verifyItems += [PSCustomObject]@{
ExpectedHash = $expectedHash
TargetFile = $targetFile
TargetFullPath = $targetFullPath
BaseDir = $baseDir
}; };
$allItems += $item; }
}; }
};
};
# --- DIRECT MATCH MODE (-m / -Match) --- $totalFiles = $verifyItems.Count;
if ($PSCmdlet.ParameterSetName -eq 'Match') { $currentIndex = 0;
if ([string]::IsNullOrWhiteSpace($Algorithm)) {
$Algorithm = Get-AlgorithmFromHashLength -HashString ($Match);
if (-not $Algorithm) { return; };
};
$expectedHash = $Match.Trim().ToLower(); $verifyItems | ForEach-Object -Parallel {
$item = $_
$algo = $using:fileAlgo
foreach ($item in ($allItems)) { if (Test-Path -Path ($item.TargetFullPath) -PathType 'Leaf') {
$actualHash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower(); $actualHash = (Get-FileHash -Path ($item.TargetFullPath) -Algorithm ($algo)).Hash.ToLower();
$targetFile = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue';
if (-not $targetFile) { $targetFile = $item.Name; }; $displayPath = Resolve-Path -Path ($item.TargetFullPath) -Relative -ErrorAction 'SilentlyContinue';
if ($targetFile.StartsWith(".\") -or $targetFile.StartsWith("./")) { $targetFile = $targetFile.Substring(2); }; if (-not $displayPath) { $displayPath = $item.TargetFile; }
if ($displayPath.StartsWith(".\") -or $displayPath.StartsWith("./")) { $displayPath = $displayPath.Substring(2); }
if ($actualHash -eq $expectedHash) { [PSCustomObject]@{
Write-Host "${targetFile}: " -NoNewline; DisplayPath = $displayPath
Status = if ($actualHash -eq $item.ExpectedHash) { "OK" } else { "FAILED" }
IsError = $false
}
} else {
$displayPath = $item.TargetFile;
if ($item.BaseDir -ne (Get-Location).Path) {
$displayPath = Join-Path -Path (Resolve-Path -Path ($item.BaseDir) -Relative -ErrorAction 'SilentlyContinue') -ChildPath ($item.TargetFile);
if ($displayPath.StartsWith(".\") -or $displayPath.StartsWith("./")) { $displayPath = $displayPath.Substring(2); }
}
[PSCustomObject]@{
DisplayPath = $displayPath
Status = "FAILED open or read"
IsError = $true
}
}
} -ThrottleLimit 16 | ForEach-Object {
$currentIndex++
if ($totalFiles -gt 0) {
Write-Progress -Activity "Verifying Checksums ($fileAlgo)" -Status "Processing file $currentIndex of $totalFiles" -PercentComplete (($currentIndex / $totalFiles) * 100);
}
Write-Host "$($_.DisplayPath): " -NoNewline;
if ($_.IsError) {
Write-Host "$($_.Status)" -ForegroundColor Red;
} elseif ($_.Status -eq "OK") {
Write-Host "OK" -ForegroundColor Green; Write-Host "OK" -ForegroundColor Green;
} else { } else {
Write-Host "${targetFile}: " -NoNewline;
Write-Host "FAILED" -ForegroundColor Red; 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));
} }
}; }
Write-Progress -Activity "Verifying Checksums ($fileAlgo)" -Completed;
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;
if ($line -match '^([a-fA-F0-9]+)\s+[* ]?(.*)$') {
$expectedHash = $Matches[1].ToLower();
$targetFile = $Matches[2].Trim().TrimStart('*');
}
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})[* ]?(.*)$') {
$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';
};
$wantCustomOut = $PSBoundParameters.ContainsKey('OutFile');
$wantAutoOut = $AutoOut.IsPresent;
if ($wantCustomOut -or $wantAutoOut) {
# Recursive wildcard auto-saves per directory
if ($Recursive -and $isWildcardGlobal) {
$groupedItems = $allItems | Group-Object DirectoryName;
foreach ($group in ($groupedItems)) {
$dirPath = $group.Name;
$filesInDir = $group.Group;
if ($wantCustomOut) {
$currentOutFile = Join-Path -Path ($dirPath) -ChildPath ($OutFile);
} else {
$currentOutFile = Join-Path -Path ($dirPath) -ChildPath "checksums.$($Algorithm.ToLower())";
};
$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 {
# Custom file OR Auto file with a wildcard
if ($wantCustomOut -or ($wantAutoOut -and $isWildcardGlobal)) {
if ($wantCustomOut) {
$singleOutFile = $OutFile;
} else {
$singleOutFile = "checksums.$($Algorithm.ToLower())";
};
$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;
}
# Auto file for explicit individual files (No wildcard)
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;
# Save directly next to the original file: <filename>.<algo>
$itemOutFile = "$($item.FullName).$($Algorithm.ToLower())";
Set-Content -Path ($itemOutFile) -Value $outputLine -Encoding utf8;
};
};
};
}
# Standard console output (No save flags passed)
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;
};
};
} }
} }
# --- GENERATION MODE ---
else {
if ([string]::IsNullOrWhiteSpace($Algorithm)) {
$Algorithm = 'SHA256';
}
end {} $wantCustomOut = $PSBoundParameters.ContainsKey('OutFile');
$wantAutoOut = $Save.IsPresent;
if ($wantCustomOut -or $wantAutoOut) {
if ($Recursive -and $isWildcardGlobal) {
$groupedItems = $allItems | Group-Object DirectoryName;
foreach ($group in ($groupedItems)) {
$dirPath = $group.Name;
$filesInDir = $group.Group;
if ($wantCustomOut) {
$currentOutFile = Join-Path -Path ($dirPath) -ChildPath ($OutFile);
} else {
$currentOutFile = Join-Path -Path ($dirPath) -ChildPath "checksums.$($Algorithm.ToLower())";
}
$totalFiles = $filesInDir.Count;
$currentIndex = 0;
$linesToWrite = @();
$filesInDir | ForEach-Object -Parallel {
$item = $_
$algo = $using:Algorithm
$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($algo)).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);
}
[PSCustomObject]@{
Item = $item
Hash = $hash
RelativePath = $relativePath
OutputLine = "${hash} ${relativePath}"
ItemOutFile = "$($item.FullName).$($algo.ToLower())"
}
} -ThrottleLimit 16 | ForEach-Object {
$currentIndex++;
if ($showProgress -and $totalFiles -gt 0) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Status "Directory: $(Split-Path $dirPath -Leaf) [$currentIndex/$totalFiles]" -PercentComplete (($currentIndex / $totalFiles) * 100);
}
$linesToWrite += $_.OutputLine;
Write-Output $_.OutputLine;
}
if ($showProgress) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Completed;
}
Set-Content -Path ($currentOutFile) -Value $linesToWrite -Encoding utf8;
}
}
else {
if ($wantCustomOut -or ($wantAutoOut -and $isWildcardGlobal)) {
if ($wantCustomOut) {
$singleOutFile = $OutFile;
} else {
$singleOutFile = "checksums.$($Algorithm.ToLower())";
}
$totalFiles = $allItems.Count;
$currentIndex = 0;
$linesToWrite = @();
$allItems | ForEach-Object -Parallel {
$item = $_
$algo = $using:Algorithm
$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($algo)).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);
}
[PSCustomObject]@{
Item = $item
Hash = $hash
RelativePath = $relativePath
OutputLine = "${hash} ${relativePath}"
ItemOutFile = "$($item.FullName).$($algo.ToLower())"
}
} -ThrottleLimit 16 | ForEach-Object {
$currentIndex++;
if ($showProgress -and $totalFiles -gt 0) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Status "Processing file $currentIndex of $totalFiles" -PercentComplete (($currentIndex / $totalFiles) * 100);
}
$linesToWrite += $_.OutputLine;
Write-Output $_.OutputLine;
}
if ($showProgress) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Completed;
}
Set-Content -Path ($singleOutFile) -Value $linesToWrite -Encoding utf8;
}
else {
$totalFiles = $allItems.Count;
$currentIndex = 0;
$allItems | ForEach-Object -Parallel {
$item = $_
$algo = $using:Algorithm
$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($algo)).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);
}
[PSCustomObject]@{
Item = $item
Hash = $hash
RelativePath = $relativePath
OutputLine = "${hash} ${relativePath}"
ItemOutFile = "$($item.FullName).$($algo.ToLower())"
}
} -ThrottleLimit 16 | ForEach-Object {
$currentIndex++;
if ($showProgress -and $totalFiles -gt 0) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Status "Processing file $currentIndex of $totalFiles" -PercentComplete (($currentIndex / $totalFiles) * 100);
}
Write-Output $_.OutputLine;
Set-Content -Path ($_.ItemOutFile) -Value $_.OutputLine -Encoding utf8;
}
if ($showProgress) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Completed;
}
}
}
}
else {
$totalFiles = $allItems.Count;
$currentIndex = 0;
$allItems | ForEach-Object -Parallel {
$item = $_
$algo = $using:Algorithm
$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($algo)).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);
}
[PSCustomObject]@{
Item = $item
Hash = $hash
RelativePath = $relativePath
OutputLine = "${hash} ${relativePath}"
ItemOutFile = "$($item.FullName).$($algo.ToLower())"
}
} -ThrottleLimit 16 | ForEach-Object {
$currentIndex++;
if ($showProgress -and $totalFiles -gt 0) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Status "Processing file $currentIndex of $totalFiles" -PercentComplete (($currentIndex / $totalFiles) * 100);
}
Write-Output $_.OutputLine;
}
if ($showProgress) {
Write-Progress -Activity "Computing Checksums ($Algorithm)" -Completed;
}
}
}