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