Public/Get-SpecMDFileHashBase64.ps1
function Get-specMDFileHashBase64 { <# .SYNOPSIS Calculates the MD5 hash of a file and returns it as a Base64-encoded string. .DESCRIPTION The Get-SpecMDFileHashBase64 function calculates the MD5 hash of a file and returns it as a Base64-encoded string. It supports two parameter sets: FilePath and FileURL. .PARAMETER FilePath Specifies the path to the file for which the MD5 hash needs to be calculated. This parameter is mandatory when using the "FilePath" parameter set. .PARAMETER FileURL Specifies the URL of the file for which the MD5 hash needs to be calculated. This parameter is mandatory when using the "FileURL" parameter set. .INPUTS None. You cannot pipe input to this function. .OUTPUTS System.String The function returns a Base64-encoded string representing the MD5 hash of the file. .EXAMPLE PS> Get-SpecMDFileHashBase64 -FilePath "C:\Files\example.txt" Calculates the MD5 hash of the file located at "C:\Files\example.txt" and returns the hash as a Base64-encoded string. .EXAMPLE PS> Get-SpecMDFileHashBase64 -FileURL "https://example.com/files/example.txt" Calculates the MD5 hash of the file located at the specified URL and returns the hash as a Base64-encoded string. .NOTES Author: andy.naftel Date: 30-May-2023 Version 1.0 - Initial function (AN) 1.1 - Incorporated getting remote file, inline comments and added comment based help (OH) 1.2 - Improved error handling #> [cmdletbinding(DefaultParameterSetName = 'FilePath')] param ( [parameter(Mandatory = $true, ParameterSetName = 'FilePath')] $FilePath, [parameter(Mandatory = $true, ParameterSetName = 'FileURL')] $FileURL ) if ($PSCmdlet.ParameterSetName -eq 'FilePath') { Write-Verbose "Calculating MD5 hash for file: $FilePath" try { $rawMD5 = (Get-FileHash -Path $FilePath -Algorithm MD5 -ea stop).Hash # Create an array of bytes to store the hash values $hashBytes = [byte[]]::new($rawMD5.Length / 2) # Convert each pair of characters from the rawMD5 string to a byte and store it in the hashBytes array For ($i = 0; $i -lt $rawMD5.Length; $i += 2) { $hashBytes[$i / 2] = [convert]::ToByte($rawMD5.Substring($i, 2), 16) } # Convert the byte array to a Base64 string and return it return [system.convert]::ToBase64String($hashBytes) } catch { Write-Error "An error occurred: $_" } } if ($PSCmdlet.ParameterSetName -eq 'FileURL') { Write-Verbose "Calculating MD5 hash for file at URL: $FileURL" try { # Send a HEAD request to the specified URL to retrieve the header information $hashCheck = Invoke-WebRequest -Method Head -Uri $FileUrl -UseBasicParsing -ea Stop # Retrieve the Content-MD5 header value and return it return $($hashCheck.Headers['Content-MD5']) } catch { Write-Error "An error occurred: $_" } } } |