PowerShell check if string is a valid Guid

1 minute read

Sometimes when dealing with external data it is required to validate input we are receiving is in the correct format.

Today I needed to validate user input was in the correct format, specifically a GUID, while PowerShell supports generation of new GUIDs easily with the New-Guid cmdlet there is no built-in method to validate input or a string is a valid GUID.

Before moving on describing the solution here’s you can easily generate GUIDs via PowerShell

# Built in PowerShell cmdlet


# Alternate with .Net accellerator

The above will both generate a valid GUID but when we need to validate input is in the correct format there is no equivalent reason for which I wrote a small function named Test-IsGuid which will return True is input string is a valid GUID or False in case it is not.

You can find the function code in my function repository and here for reference:

function Test-IsGuid
        [Parameter(Mandatory = $true)]

    # Define verification regex
    [regex]$guidRegex = '(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$'

    # Check guid against regex
    return $ObjectGuid -match $guidRegex

Here are couple of examples to show how the function works:

# Test valid guid
Test-IsGuid -ObjectGuid '4a6b7fcb-f1e4-42c8-ae6f-d3862dbbcbca'


# Test arbitrary string
Test-IsGuid -ObjectGuid '4444-23-ec-789'


Test-IsGuid -ObjectGuid '(CA761232-ED42-11CE-BACD-00AA0057B223)'


Hope you will find this useful!