Skip to content

Instantly share code, notes, and snippets.

@Dadangdut33
Created November 28, 2023 08:52
Show Gist options
  • Save Dadangdut33/afc7a51cb6c7c3e17b6dc8d28d1d47b9 to your computer and use it in GitHub Desktop.
Save Dadangdut33/afc7a51cb6c7c3e17b6dc8d28d1d47b9 to your computer and use it in GitHub Desktop.
Function to Get Checksum of File with Powershell and write it (SHA1, SHA256, SHA384, SHA512, MD5)

About

Powershell support the following hashing algorithm:

  • SHA1
  • SHA256
  • SHA384
  • SHA512
  • MD5

I created simple script that you can add to your powershell $PROFILE

The script

function Get-FileChecksum {
    param (
        [string]$FilePath,
        [string]$Algorithm = "MD5",
        [switch]$WriteToFile
    )

    if (-not (Test-Path -Path $FilePath -PathType Leaf)) {
        Write-Error "File not found: $FilePath"
        return
    }

    $hash = Get-FileHash -Path $FilePath -Algorithm $Algorithm | Select-Object -ExpandProperty Hash

    if ($WriteToFile) {
        $checksumFileName = "$FilePath.$Algorithm"
        $hash | Set-Content -Path $checksumFileName -Force
        Write-Output "Checksum written to $checksumFileName"
    } else {
        Write-Output $hash
    }
}

Usage examples:

  1. Calculate checksum with default algorithm set (MD5) and display it:
Get-FileChecksum -FilePath "C:\Path\To\YourInstaller.exe"
  1. Calculate SHA-256 checksum and write it to a file:
Get-FileChecksum -FilePath "C:\Path\To\YourInstaller.exe" -Algorithm SHA256 -WriteToFile

This will write the checksum to a file with the format "YourInstaller.exe.SHA256" in the same directory as the installer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment