Generate Unique GUID in PowerShell

less than 1 minute read

In Azure ARM / Bicep templates, there is a function called guid() which allows you to generate a unique GUID. You can use this function as many times as you want, as long as the input strings are the same, the output GUID will always be the same.

I use the guid() function a lot when working on Bicep code, however, few weeks ago I needed to generate unique GUIDs within a PowerShell script. I couldn’t find any existing code examples, so I came up with my own:

Function GenerateGuid {
  param (
    [parameter(Mandatory = $true)]
  $enc = [system.Text.Encoding]::UTF8
  $sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
  $joinedStrings = $inputStrings -join "-"
  $joinedStringsByteArray = $enc.GetBytes($joinedStrings)
  $joinedStringsHash = [system.Convert]::toBase64String($($sha.ComputeHash($joinedStringsByteArray)))
  $joinedStringsHashTruncated = $joinedStringsHash.Substring(0, 16)
  $joinedStringsHashTruncatedByteArray = $enc.GetBytes($joinedStringsHashTruncated)
  $guid = [guid]::new($joinedStringsHashTruncatedByteArray)

Same as the Bicep guid() function, as long as the array of strings (and the positions) stay the same, you will get the same GUID every time you run the function:


Leave a comment