Validating a GUID with PowerShell

less than 1 minute read

For some recent Microsoft Graph scripts I wanted to translate some Azure AD Object ID / GUID entries to their respective display name. The array with the GUID’s contained already some readable text. Of course I only wanted to translate the GUID entries with according Graph API requests. Otherwise the Graph requests would fail. Google offered only some fancy regex functions and helpers but I had that .NET function in my mind which looks much nicer compared to whatever regex pattern that I don’t understand.

"applications": {
    "includeApplications": [
    "797f4846-ba00-4fd7-ba43-dac1f8f63013",
    "Office365"
    ]
}

So I needed a way to test a string for a valid GUID and only invoking the Graph calls for GUID values.

Matching a GUID with a regex

I found the following regex on this site:

"d815c3bc-9c49-4633-9d16-29808242d063" -match '(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$'

Matching a GUID with the .NET method

Instead of the complex regex we can invoke this nice .NET member method which returns true or false based on the input:

[guid]::TryParse("d815c3bc-9c49-4633-9d16-29808242d063", $([ref][guid]::Empty))

I guess that’s much more convenient.

Helper Function

Here’s a helper function which can be used in PowerShell scripts:

Hope this saves you some time.

Happy GUID’ing.

Comments