Share via


Getting an SHA256 Hash

To steal from the .DESCRIPTION section of the comment-based help:

“Yes, PowerShell3 has Get-FileHash, but I have some PSH V2 environments that don't benefit from that yummy goodness.”

 function Get-Sha256Hash
{
    <#

    .SYNOPSIS
    Get SHA256 checksum

    .DESCRIPTION
    Get SHA256 checksum.  Yes, PowerShell3 has Get-FileHash, but I have some PSH V2 environments that don't benefit from that yummy goodness.

    .PARAMETER Path
    File for which to generate checksum

    .NOTES
    Who         What        When        Why
    timdunn     V1.0        2014-01-27  Initial creation.

    #>


    param
    (
        [string]$Path = $null
    );

    if (!$Path)
    {
        Write-Warning "$($MyInvocation.MyCommand.Name) -Path not specified.  Stopping.";
        return;

    } # if (!$Path)
    elseif (Test-Path $Path)
    {
        if ((Get-Item $Path).PsIsContainer)
        {

            Write-Warning "$($MyInvocation.MyCommand.Name) -Path '$Path' is a folder.  Stopping.";
            return;

        } # if ((Get-Item $Path).PsIsContainer)

    } # if (Test-Path $Path)
    else
    {
        Write-Warning "$($MyInvocation.MyCommand.Name) -Path '$Path' not found.  Stopping.";
        return;

    } # if (Test-Path $Path)
     $Path = (Resolve-Path -Path $Path).ProviderPath;

    $ObjectCheckSum = New-Object -TypeName System.Security.Cryptography.Sha256CryptoServiceProvider;

    [System.BitConverter]::ToString(
        $ObjectCheckSum.ComputeHash(
            [System.IO.File]::Open(
                $Path,
                [System.IO.Filemode]::Open, 
                [System.IO.FileAccess]::Read,
                [System.IO.FileShare]::ReadWrite
            )
        )
    );

} # function Get-Sha256Hash