Skip to main content

PowerShell function to generate a SHA256 hash from a file. See Generate Hash from File in PowerShell for a more robust version.

[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
function Sha256File([string] $filePath)
{
    if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf))
    {
        return $null
    }

    [System.IO.Stream] $file = $null;
    [System.Security.Cryptography.SHA256] $hasher = $null;

    try
    {
        $hasher = [System.Security.Cryptography.SHA256]::Create()
        $file = [System.IO.File]::OpenRead($filePath)

        return [System.BitConverter]::ToString($hasher.ComputeHash($file))
    }
    finally
    {
        if ($null -ne $file)
        {
            $file.Dispose()
        }

        if ($null -ne $hasher)
        {
            $hasher.Dispose()
        }
    }
}

#
# Example:
[string] $checksumFile = "path/to/checksum/file.zip.sha256sum"
[string] $fileToHash = "path/to/hash/file.zip"
[string] $hash = Sha256File $fileToHash
if ( (!(Test-Path $checksumFile)) -or ($hash -ne (Get-Content $checksumFile)) )
{
    Write-Error -Message "Missing or changed hash for file '$fileToHash'..."
}