waypoit debuguing

This commit is contained in:
2026-09-25 15:25:19 -06:00
parent 3f03b2a0f3
commit 776a52c3c3
+78 -95
View File
@@ -5,35 +5,40 @@ param(
[Parameter(Position = 0, ParameterSetName = 'Match', ValueFromPipeline = $true)] [Parameter(Position = 0, ParameterSetName = 'Match', ValueFromPipeline = $true)]
[string[]]$FilePath, [string[]]$FilePath,
# Output file to save generated checksums (-o mode) # Output file switch (-o) - auto generates file based on rules
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')] [Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
[Alias('o', '-outfile')] [Alias('o', 'out')]
[switch]$SaveToFile,
# Custom Output file name (-f)
[Parameter(Mandatory = $false, ParameterSetName = 'Generate')]
[Alias('f', 'outfile')]
[string]$OutFile, [string]$OutFile,
# File containing checksums to verify (-c mode) # File containing checksums to verify (-c mode)
[Parameter(Mandatory = $false, ParameterSetName = 'Verify')] [Parameter(Mandatory = $false, ParameterSetName = 'Verify')]
[Alias('c', '-check')] [Alias('c', 'check')]
[string]$Check, [string]$Check,
# Direct checksum hash string to match against (-m mode) # Direct checksum hash string to match against (-m mode)
[Parameter(Mandatory = $true, ParameterSetName = 'Match')] [Parameter(Mandatory = $true, ParameterSetName = 'Match')]
[Alias('m', '-match')] [Alias('m', 'match')]
[string]$Match, [string]$Match,
# Hashing algorithm to use (Defaults to SHA256) # Hashing algorithm to use (Defaults to SHA256)
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[Alias('a', 'algo', '-algo', '-algorithm')] [Alias('a', 'algo', 'algorithm')]
[ValidateSet('SHA1', 'SHA256', 'SHA384', 'SHA512', 'MD5')] [ValidateSet('SHA1', 'SHA256', 'SHA384', 'SHA512', 'MD5')]
[string]$Algorithm, [string]$Algorithm,
# Recursive flag (-r, -recursive, --recursive) # Recursive flag (-r)
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[Alias('r', '-recursive')] [Alias('r', 'recursive')]
[switch]$Recursive, [switch]$Recursive,
# Help flag (-h, -Help, --Help, --H) # Help flag (-h)
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[Alias('h', '-h', '-help')] [Alias('h', 'help')]
[switch]$Help [switch]$Help
) )
@@ -44,9 +49,9 @@ NAME
checksum - Compute and verify message digests / file checksums checksum - Compute and verify message digests / file checksums
SYNOPSIS SYNOPSIS
.\checksum.ps1 [-FilePath] <string[]> [-OutFile <string>] [-Algorithm <string>] [-Recursive] .\checksum.ps1 [-FilePath] <string[]> [-o] [-OutFile <string>] [-Algorithm <string>] [-r]
.\checksum.ps1 [-FilePath] <string[]> -Match <string> [-Algorithm <string>] [-Recursive] .\checksum.ps1 [-FilePath] <string[]> -Match <string> [-Algorithm <string>] [-r]
.\checksum.ps1 -Check <string> [-Algorithm <string>] [-Recursive] .\checksum.ps1 -Check <string> [-Algorithm <string>] [-r]
.\checksum.ps1 -Help .\checksum.ps1 -Help
DESCRIPTION DESCRIPTION
@@ -54,21 +59,20 @@ DESCRIPTION
Outputs hash values in standard Linux utility format (<hash> <filename>). Outputs hash values in standard Linux utility format (<hash> <filename>).
Ignores checksum files (.md5, .sha1, .sha256, .sha384, .sha512) unless explicitly passed. Ignores checksum files (.md5, .sha1, .sha256, .sha384, .sha512) unless explicitly passed.
NOTE: All flags and parameters are completely case-insensitive
(e.g., -r, -R, --Recursive, and --recursive are treated identically).
PARAMETERS PARAMETERS
-FilePath <string[]> -FilePath <string[]>
Specifies the path to one or more files to hash. Accepts wildcards (*). Specifies the path to one or more files to hash. Accepts wildcards (*).
-o, -OutFile, --OutFile <string> -o, -Out, --Out <switch>
Specifies an output file to save the checksum results to. Enables writing checksum results to an auto-named file.
If passed as an empty string (e.g. -o ""), the file is auto-named:
- If input has a wildcard (*), outputs to 'checksums.<algo>' - If input has a wildcard (*), outputs to 'checksums.<algo>'
- If no wildcard is used, outputs to '<filename>.<algo>' per file. - If no wildcard is used, outputs to '<filename>.<algo>' per file.
When combined with -r and *, it auto-generates checksum files When combined with -r and *, it auto-generates checksum files
inside the current working directory and each subdirectory recursively. 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> -r, -Recursive, --Recursive <switch>
Recursively generate or verify checksums in subdirectories. Recursively generate or verify checksums in subdirectories.
@@ -79,30 +83,26 @@ PARAMETERS
-m, -Match, --Match <string> -m, -Match, --Match <string>
Compare the computed hash of the target file(s) against a specific hash string. Compare the computed hash of the target file(s) against a specific hash string.
-a, -Algorithm, --Algorithm, -Algo, --Algo <string> -a, -Algorithm, --Algorithm <string>
Specifies the cryptographic hash algorithm to use. Specifies the cryptographic hash algorithm to use.
Supported values: SHA1, SHA256 (default), SHA384, SHA512, MD5. Supported values: SHA1, SHA256 (default), SHA384, SHA512, MD5.
If omitted in -c or -m mode, the algorithm is auto-detected by hash length. If omitted in -c or -m mode, the algorithm is auto-detected by hash length.
-h, -Help, --Help, --H <switch> -h, -Help, --Help <switch>
Display this help message. Display this help message.
EXAMPLES EXAMPLES
1. Compute SHA256 checksum for a single file: 1. Compute SHA256 checksum for a single file:
.\checksum.ps1 myfile.iso .\checksum.ps1 myfile.iso
2. Compute checksums for all files and write to a file while showing output: 2. Compute checksums for all files and auto-write to files (-o flag):
.\checksum.ps1 * --OutFile checksums.sha256 .\checksum.ps1 * -r -o
3. Auto-generate per-directory checksum files recursively for all files: 3. Verify checksums from verification files recursively:
.\checksum.ps1 * -r -o "" .\checksum.ps1 -c checksums.sha256 -r
4. Verify checksums from verification files recursively:
.\checksum.ps1 --Check checksums.sha256 --Recursive
'@ '@
} }
# Helper function to auto-detect hash algorithm based on string character length
function Get-AlgorithmFromHashLength { function Get-AlgorithmFromHashLength {
param([string]$HashString) param([string]$HashString)
@@ -121,19 +121,22 @@ EXAMPLES
} }
process { process {
# Match help arguments passed either as switch (-h, -Help) or positional string ('help', 'h', '--help', etc.) # Bulletproof help check (catches --help passed positionally)
$isHelpRequested =$Help.IsPresent -or ( $helpInPath =$false
$FilePath -and$FilePath.Count -eq 1 -and ( if ($FilePath) {
$FilePath[0] -match '^(?i)[-/]{0,2}(h\vert{}help)$' foreach ($p in ($FilePath)) {
) if ($p -match '^(?i)[-/]{1,2}(h\vert{}help)$') {
) $helpInPath =$true
break
}
}
}
if ($isHelpRequested) { if ($Help.IsPresent -or$helpInPath) {
Show-Help Show-Help
return return
} }
# Normalize explicit algorithm input if provided
if (-not [string]::IsNullOrWhiteSpace($Algorithm)) { if (-not [string]::IsNullOrWhiteSpace($Algorithm)) {
$Algorithm =$Algorithm.ToUpper() $Algorithm =$Algorithm.ToUpper()
} }
@@ -149,36 +152,35 @@ process {
$isWildcardGlobal =$false; $isWildcardGlobal =$false;
$skipExtensions = @('.md5', '.sha1', '.sha256', '.sha384', '.sha512'); $skipExtensions = @('.md5', '.sha1', '.sha256', '.sha384', '.sha512');
# Delimiting collection in parentheses prevents space-stripping errors
foreach ($pathEntry in ($FilePath)) { foreach ($pathEntry in ($FilePath)) {
$isWildcard = ($pathEntry -match '\*'); $isWildcard = ($pathEntry -match '\*');
if ($isWildcard) { $isWildcardGlobal =$true } if ($isWildcard) { $isWildcardGlobal =$true }
$resolvedItems = @(); $resolvedItems = @();
if ($Recursive) { if ($Recursive) {
$resolvedItems = Get-ChildItem -Path$pathEntry -Recurse -File -ErrorAction SilentlyContinue # Parens around variables prevent space-stripping crashes
$resolvedItems = Get-ChildItem -Path ($pathEntry) -Recurse -File -ErrorAction 'SilentlyContinue'
} else { } else {
if ($isWildcard -or ($pathEntry -match '\?')) { if ($isWildcard -or ($pathEntry -match '\?')) {
$resolvedItems = Get-ChildItem -Path$pathEntry -File -ErrorAction SilentlyContinue $resolvedItems = Get-ChildItem -Path ($pathEntry) -File -ErrorAction 'SilentlyContinue'
} else { } else {
$resolvedItems = Get-Item -Path$pathEntry -ErrorAction SilentlyContinue $resolvedItems = Get-Item -Path ($pathEntry) -ErrorAction 'SilentlyContinue'
} }
} }
if (-not $resolvedItems) { if (-not $resolvedItems) {
Write-Error "checksum: $pathEntry`: No such file or directory" Write-Error "checksum: $($pathEntry)`: No such file or directory"
continue continue
} }
$explicitFileFound = $false; $explicitFileFound = $false;
if ((-not $isWildcard) -and (Test-Path -Path $pathEntry -PathType Leaf)) { if ((-not $isWildcard) -and (Test-Path -Path ($pathEntry) -PathType 'Leaf')) {
$explicitFileFound = $true $explicitFileFound = $true
} }
foreach ($item in ($resolvedItems)) { foreach ($item in ($resolvedItems)) {
if ($item.PSIsContainer) { continue } if ($item.PSIsContainer) { continue }
# Feature 1: Skip checksum extension files unless they were named explicitly
if (-not $explicitFileFound) { if (-not $explicitFileFound) {
if ($skipExtensions -contains $item.Extension.ToLower()) { if ($skipExtensions -contains $item.Extension.ToLower()) {
continue continue
@@ -192,16 +194,15 @@ process {
# --- DIRECT MATCH MODE (-m / -Match) --- # --- DIRECT MATCH MODE (-m / -Match) ---
if ($PSCmdlet.ParameterSetName -eq 'Match') { if ($PSCmdlet.ParameterSetName -eq 'Match') {
if ([string]::IsNullOrWhiteSpace($Algorithm)) { if ([string]::IsNullOrWhiteSpace($Algorithm)) {
$Algorithm = Get-AlgorithmFromHashLength -HashString $Match $Algorithm = Get-AlgorithmFromHashLength -HashString ($Match)
if (-not $Algorithm) { return } if (-not $Algorithm) { return }
Write-Verbose "Auto-detected algorithm: $Algorithm"
} }
$expectedHash = $Match.Trim().ToLower(); $expectedHash = $Match.Trim().ToLower();
foreach ($item in ($allItems)) { foreach ($item in ($allItems)) {
$actualHash = (Get-FileHash -Path $item.FullName -Algorithm $Algorithm).Hash.ToLower() $actualHash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
$targetFile = Resolve-Path -Path $item.FullName -Relative -ErrorAction SilentlyContinue $targetFile = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue'
if (-not $targetFile) { $targetFile = $item.Name } if (-not $targetFile) { $targetFile = $item.Name }
if ($targetFile.StartsWith(".\")) { $targetFile = $targetFile.Substring(2) } if ($targetFile.StartsWith(".\")) { $targetFile = $targetFile.Substring(2) }
@@ -218,22 +219,21 @@ process {
elseif ($PSCmdlet.ParameterSetName -eq 'Verify') { elseif ($PSCmdlet.ParameterSetName -eq 'Verify') {
$checkFiles = @(); $checkFiles = @();
if ($Recursive) { if ($Recursive) {
# Find all files matching the name of $Check recursively $checkFileName = Split-Path -Path ($Check) -Leaf
$checkFileName = Split-Path $Check -Leaf $checkFiles = Get-ChildItem -Path '.\' -Filter ($checkFileName) -Recurse -File -ErrorAction 'SilentlyContinue'
$checkFiles = Get-ChildItem -Path .\ -Filter $checkFileName -Recurse -File -ErrorAction SilentlyContinue
} else { } else {
if (Test-Path -Path $Check -PathType Leaf) { if (Test-Path -Path ($Check) -PathType 'Leaf') {
$checkFiles = @(Get-Item -Path $Check) $checkFiles = @(Get-Item -Path ($Check))
} }
} }
if (-not $checkFiles -or $checkFiles.Count -eq 0) { if (-not $checkFiles -or $checkFiles.Count -eq 0) {
Write-Error "checksum: $Check`: No such file or directory" Write-Error "checksum: $($Check)`: No such file or directory"
return return
} }
foreach ($cf in ($checkFiles)) { foreach ($cf in ($checkFiles)) {
$lines = Get-Content -Path$cf.FullName $lines = Get-Content -Path ($cf.FullName)
$baseDir =$cf.DirectoryName $baseDir =$cf.DirectoryName
$fileAlgo =$Algorithm $fileAlgo =$Algorithm
@@ -241,8 +241,7 @@ process {
foreach ($line in ($lines)) { foreach ($line in ($lines)) {
if ([string]::IsNullOrWhiteSpace($line) -or$line.StartsWith("#")) { continue } if ([string]::IsNullOrWhiteSpace($line) -or$line.StartsWith("#")) { continue }
if ($line -match '^([a-fA-F0-9]+)\s+') { if ($line -match '^([a-fA-F0-9]+)\s+') {
$fileAlgo = Get-AlgorithmFromHashLength -HashString$Matches[1] $fileAlgo = Get-AlgorithmFromHashLength -HashString ($Matches[1])
if ($fileAlgo) { Write-Verbose "Auto-detected algorithm: $fileAlgo in $($cf.Name)" }
break break
} }
} }
@@ -252,16 +251,11 @@ process {
foreach ($line in ($lines)) { foreach ($line in ($lines)) {
if ([string]::IsNullOrWhiteSpace($line) -or$line.StartsWith("#")) { continue } if ([string]::IsNullOrWhiteSpace($line) -or$line.StartsWith("#")) { continue }
if ($line -match '^([a-fA-F0-9]+)\s+[* ]?(.*)$') { if ($line -match '^([a-fA-F0-9]+)\s+[* ]?(.*)$') {$expectedHash = $Matches[1].ToLower()$targetFile = $Matches[2].Trim().TrimStart('*')$targetFullPath = Join-Path -Path ($baseDir) -ChildPath ($targetFile)
$expectedHash =$Matches[1].ToLower()
$targetFile =$Matches[2].Trim().TrimStart('*')
# Resolve path relative to where the check file currently resides
$targetFullPath = Join-Path -Path $baseDir -ChildPath$targetFile
if (Test-Path -Path $targetFullPath -PathType Leaf) {$actualHash = (Get-FileHash -Path $targetFullPath -Algorithm$fileAlgo).Hash.ToLower() if (Test-Path -Path ($targetFullPath) -PathType 'Leaf') {$actualHash = (Get-FileHash -Path ($targetFullPath) -Algorithm ($fileAlgo)).Hash.ToLower()
$displayPath = Resolve-Path -Path$targetFullPath -Relative -ErrorAction SilentlyContinue $displayPath = Resolve-Path -Path ($targetFullPath) -Relative -ErrorAction 'SilentlyContinue'
if (-not $displayPath) { $displayPath =$targetFile } if (-not $displayPath) { $displayPath =$targetFile }
if ($displayPath.StartsWith(".\")) { $displayPath =$displayPath.Substring(2) } if ($displayPath.StartsWith(".\")) { $displayPath =$displayPath.Substring(2) }
@@ -273,16 +267,13 @@ process {
Write-Host "FAILED" -ForegroundColor Red Write-Host "FAILED" -ForegroundColor Red
} }
} else { } else {
# Format missing path nicely
$displayPath =$targetFile $displayPath =$targetFile
if ($baseDir -ne (Get-Location).Path) {$displayPath = Join-Path -Path (Resolve-Path -Path $baseDir -Relative -ErrorAction SilentlyContinue) -ChildPath$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) } if ($displayPath.StartsWith(".\")) { $displayPath =$displayPath.Substring(2) }
} }
Write-Host "${displayPath}: " -NoNewline Write-Host "${displayPath}: " -NoNewline
Write-Host "FAILED open or read" -ForegroundColor Red Write-Host "FAILED open or read" -ForegroundColor Red
} }
} else {
Write-Warning "checksum: improperly formatted line in $($cf.Name):$line"
} }
} }
} }
@@ -292,12 +283,10 @@ process {
if ([string]::IsNullOrWhiteSpace($Algorithm)) {$Algorithm = 'SHA256' if ([string]::IsNullOrWhiteSpace($Algorithm)) {$Algorithm = 'SHA256'
} }
# Check if -o / -OutFile parameter was explicitly invoked # Enable output if the switch is used OR an explicit file is provided
$wantOutFile =$PSBoundParameters.ContainsKey('OutFile'); $wantOutFile = $SaveToFile.IsPresent -or (-not [string]::IsNullOrWhiteSpace($OutFile));
$outFilename =$OutFile;
if ($wantOutFile) { if ($wantOutFile) {
# Feature 2 & 3: Recursive, Wildcard + Passed output flag splits hashes strictly into localized directory files
if ($Recursive -and$isWildcardGlobal) { if ($Recursive -and$isWildcardGlobal) {
$groupedItems =$allItems | Group-Object DirectoryName $groupedItems =$allItems | Group-Object DirectoryName
@@ -305,44 +294,40 @@ process {
$dirPath =$group.Name $dirPath =$group.Name
$filesInDir =$group.Group $filesInDir =$group.Group
if ([string]::IsNullOrWhiteSpace($outFilename)) { if ([string]::IsNullOrWhiteSpace($OutFile)) {
$currentOutFile = Join-Path -Path$dirPath -ChildPath "checksums.$($Algorithm.ToLower())" $currentOutFile = Join-Path -Path ($dirPath) -ChildPath "checksums.$($Algorithm.ToLower())"
} else { } else {
$currentOutFile = Join-Path -Path $dirPath -ChildPath$outFilename $currentOutFile = Join-Path -Path ($dirPath) -ChildPath ($OutFile)
} }
# Clear existing file before iterating $null = New-Item -Path ($currentOutFile) -ItemType 'File' -Force
$null = New-Item -Path$currentOutFile -ItemType File -Force
foreach ($item in ($filesInDir)) {$hash = (Get-FileHash -Path $item.FullName -Algorithm$Algorithm).Hash.ToLower() foreach ($item in ($filesInDir)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
$relativePath =$item.Name # Localization relies purely on internal filenames $relativePath =$item.Name
$outputLine = "$hash$relativePath" $outputLine = "$hash$relativePath"
Add-Content -Path $currentOutFile -Value$outputLine Add-Content -Path ($currentOutFile) -Value ($outputLine)
Write-Output $outputLine Write-Output $outputLine
} }
} }
} }
# Non-localized standard generation (Singular master file, or Per-file auto naming)
else { else {
$singleOutFile =$null; $singleOutFile =$null;
# Check for standard auto naming rules if ([string]::IsNullOrWhiteSpace($OutFile)) {
if ([string]::IsNullOrWhiteSpace($outFilename)) {
if ($isWildcardGlobal) {$singleOutFile = "checksums.$($Algorithm.ToLower())" if ($isWildcardGlobal) {$singleOutFile = "checksums.$($Algorithm.ToLower())"
} }
} else { } else {
$singleOutFile =$outFilename $singleOutFile =$OutFile
} }
# Clear master file if consolidating to one file
if ($singleOutFile) { if ($singleOutFile) {
$null = New-Item -Path$singleOutFile -ItemType File -Force $null = New-Item -Path ($singleOutFile) -ItemType 'File' -Force
} }
foreach ($item in ($allItems)) {$hash = (Get-FileHash -Path $item.FullName -Algorithm$Algorithm).Hash.ToLower() foreach ($item in ($allItems)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
$relativePath = Resolve-Path -Path$item.FullName -Relative -ErrorAction SilentlyContinue $relativePath = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue'
if (-not $relativePath) { $relativePath =$item.Name } if (-not $relativePath) { $relativePath =$item.Name }
if ($relativePath.StartsWith(".\")) { if ($relativePath.StartsWith(".\")) {
$relativePath =$relativePath.Substring(2) $relativePath =$relativePath.Substring(2)
@@ -351,23 +336,21 @@ process {
$outputLine = "$hash$relativePath" $outputLine = "$hash$relativePath"
if ($singleOutFile) { if ($singleOutFile) {
Add-Content -Path $singleOutFile -Value$outputLine Add-Content -Path ($singleOutFile) -Value ($outputLine)
} else { } else {
# Single-file auto naming (<filename>.<algo>)
$currentOutFile = "$($item.FullName).$($Algorithm.ToLower())" $currentOutFile = "$($item.FullName).$($Algorithm.ToLower())"
$null = New-Item -Path$currentOutFile -ItemType File -Force $null = New-Item -Path ($currentOutFile) -ItemType 'File' -Force
Add-Content -Path $currentOutFile -Value$outputLine Add-Content -Path ($currentOutFile) -Value ($outputLine)
} }
Write-Output $outputLine Write-Output $outputLine
} }
} }
} }
# Standard fallback if no -o was invoked: Stream perfectly to console
else { else {
foreach ($item in ($allItems)) {$hash = (Get-FileHash -Path $item.FullName -Algorithm$Algorithm).Hash.ToLower() foreach ($item in ($allItems)) {$hash = (Get-FileHash -Path ($item.FullName) -Algorithm ($Algorithm)).Hash.ToLower()
$relativePath = Resolve-Path -Path$item.FullName -Relative -ErrorAction SilentlyContinue $relativePath = Resolve-Path -Path ($item.FullName) -Relative -ErrorAction 'SilentlyContinue'
if (-not $relativePath) { $relativePath =$item.Name } if (-not $relativePath) { $relativePath =$item.Name }
if ($relativePath.StartsWith(".\")) { if ($relativePath.StartsWith(".\")) {
$relativePath =$relativePath.Substring(2) $relativePath =$relativePath.Substring(2)