Public/Compare-FileHash.ps1
|
function Compare-FileHash { <# .SYNOPSIS Compares the hashes of two files and shows visual differences. .DESCRIPTION This function calculates the hashes of two files and compares them. If they differ, it displays a per-character diff using ANSI colors. .INPUTS System.String .OUTPUTS None .PARAMETER ReferencePath The first file to compare. .PARAMETER DifferencePath The second file to compare. .EXAMPLE Compare-FileHash -ReferencePath "C:\file1.txt" -DifferencePath "C:\file2.txt" .NOTES Terminal must support ANSI colors for colorized output. #> [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0)] [string]$ReferencePath, [Parameter(Mandatory, Position = 1)] [string]$DifferencePath ) function Show-HashDiff { param ( [string]$Hash1, [string]$Hash2 ) if ($Hash1.Length -ne $Hash2.Length) { Write-Warning "Hash lengths do not match. Cannot visually compare." return } $diff = "" for ($i = 0; $i -lt $Hash1.Length; $i++) { if ($Hash1[$i] -eq $Hash2[$i]) { $diff += "`e[32m$($Hash2[$i])`e[0m" # Green } else { $diff += "`e[31m$($Hash2[$i])`e[0m" # Red } } Write-Host "Reference Hash : $Hash1" Write-Host "Difference Hash : $diff" } # Ensure both files exist if (-not (Test-Path -Path $ReferencePath)) { Write-Error "Reference file '$ReferencePath' does not exist." return } if (-not (Test-Path -Path $DifferencePath)) { Write-Error "Difference file '$DifferencePath' does not exist." return } # Get file hashes $leftHash = Get-FileHash -Path $ReferencePath $rightHash = Get-FileHash -Path $DifferencePath # Comparison result $areEqual = $leftHash.Hash -eq $rightHash.Hash if ($areEqual) { Write-Host "✅ Hashes match." -ForegroundColor Green } else { Write-Host "❌ Hashes do NOT match!" -ForegroundColor Red Show-HashDiff -Hash1 $leftHash.Hash -Hash2 $rightHash.Hash } } |