PowerShell Checksum Utility

Sometimes when a file is available for download on the internet, a checksum is provided so that its integrity can be checked, to make sure that it hasn't become corrupt in transit. Below is an example of how PowerShell can be used to calculate the checksum of a downloaded file and compare it with the one provided.

Firstly, three pieces of information are required to be entered, the file path, the hashing algorithm to use, such as SHA512, together with the checksum that has been provided. The checksum of the downloaded file is then calculated and compared with the one provided. Both the file path and hashing algorithm are checked for their validity.

# Clear the console window.
Clear-Host

# Variables for file path, chosen hashing algorithm and checksum to compare.
[string] $filePath = $null
[string] $hashType = $null
[string] $checksumToCompare = $null

# Array of possible hashing algorithms.
[string[]] $validHashType = "MD5", "SHA1", "SHA256", "SHA384", "SHA512"

# Request entry of a file path.
$filePath = Read-Host "Please enter a file path: "
Write-Host "You entered: $filePath"

# Check if file exists.
if (-not (Test-Path $filePath))
{

    # Display invalid file path message and exit.
    Write-Host "Invalid file path."
    exit

}

Write-Host ""

# Request entry of a hashing algorithm.
$hashType = Read-Host "Please enter a hashing algorithm: "
Write-Host "You entered: " $hashType.ToUpper()

# Check for a valid hashing algorithm.
if (-not ($validHashType.Contains($hashType.ToUpper())))
{

    # Display invalid hashing algorithm message and exit.
    Write-Host "Invalid hashing algorithm."
    exit

}

Write-Host ""

# Request entry of the checksum to compare.
$checksumToCompare = Read-Host "Please enter a checksum to compare: "
Write-Host "You entered: " $checksumToCompare.ToUpper()

Write-Host ""

# Calculate and display the file hash.
$checksumResult = Get-FileHash -Path $filePath -Algorithm $hashType.ToUpper()
Write-Host "Resulting checksum: " $checksumResult.Hash

Write-Host ""

# Compare checksums and display the result.
if ($checksumToCompare.ToUpper() -eq $checksumResult.Hash)
{

    Write-Host "The checksums match."

}
else
{

    Write-Host "The checksums don't match."

}