Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Function to hash any string passed to it - Provide text to hash as parameter
function stringHash
{
<#
.SYNOPSIS
Function to hash any string passed to it.
.DESCRIPTION
Provide text you would like to generate a hash value for as an argument and the function will return an SHA256 hash of the text.
.NOTES
The script returns the hash value directly to the script or command line. If you want to store the value, you need to call the function as the value of a variable.
.EXAMPLE
stringHash "Hello World"
$hashResults = stringHash "Hello World"
$hashResults = stringHash $SomeVariable
#>
param (
[Parameter(Mandatory)]
[string]$textToHash
)
# Build hasher
$hasher = new-object System.Security.Cryptography.SHA256Managed
# Format string
$toHash = [System.Text.Encoding]::UTF8.GetBytes($textToHash)
# Hash string
$hashByteArray = $hasher.ComputeHash($toHash)
# Build output
foreach($byte in $hashByteArray)
{
$hashResults += $byte.ToString()
}
# Return text string hash
return $hashResults
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment