Validating File Hashes in PowerShell

Validating File Hashes in PowerShell

PowerShell (from version 4 onwards I think) has a Get-FileHash cmdlet that lets you generate a quick-and-dirty md5 hash of a file. This is particularly useful if you are running a process which may or may not update a lot of files and you can't be sure what the effects have been.

Here I iterate through a folder, recording the original version of the hash against the file name. We then run the potentially destructive tool and re-examine the files and report on changes. For simplicity I am just writing text out to the screen and using red for failures, green for each match and yellow for new files created in the mystery process.


$OriginalHashes = @{ }

# Record pre-whatever state.
Get-ChildItem -Path $here -Filter *.* | ForEach-Object {

	[string]$File = $_.Name
	[string]$Hash =  (Get-FileHash $_.FullName).Hash

	$OriginalHashes.Add($File, $Hash)
}

# ... Do something potentially destructive

# Regenerate hashes and compare to existing.
Get-ChildItem -Path $here -Filter *.* | ForEach-Object {

	[string]$File = $_.Name
	[string]$NewHash =  (Get-FileHash $_.FullName).Hash

	If ($OriginalHashes.ContainsKey($File)) {

		$OldHash = $OriginalHashes[$File]

		If ($OldHash -ne $NewHash) {
				
			Write-Host "Hash values differ for $File - old: $OldHash new: $NewHash" -ForegroundColor Red

		} Else {

			Write-Host "Hashes for $File match" -ForegroundColor Green
		}

	} Else {
			
		Write-Host "New file: $File"  -ForegroundColor Yellow
	}
}