PowerShell – Check if a string is valid GUID or not

In PowerShell, we can easily generate a new GUID (Globally Unique Identifier) using the New-GUID cmdlet, but we do not have a built-in command to validate and find a string is a valid GUID or not.

The below command generates a new GUID value.

PS C:\ > New-GUID
077e4982-4dd1-4d1f-ba18-d36e419971c1

Check GUID is valid or not using Regex

We can use the Regular Expression (Regex) to validate the given string is a valid GUID text or not.

$GUID = "077e4982-4dd1-4d1f-ba18-d36e419971c1"
$GUID -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")

Validate GUID using TryParse method

Alternatively, we can also use the TryParse method from the .NET Class “System.Guid” to ensure the given value is an actual GUID or not.

$StringGuid = "077e4982-4dd1-4d1f-ba18-d36e419971c1"
$ObjectGuid = [System.Guid]::empty
# Returns True if successfully parsed, otherwise returns False.
[System.Guid]::TryParse($StringGuid,[System.Management.Automation.PSReference]$ObjectGuid)

To make the work simple, we can create a function to validate GUID and return the status.

function Test-IsGuid
{
    [OutputType([bool])]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]$StringGuid
    )

   $ObjectGuid = [System.Guid]::empty
   return [System.Guid]::TryParse($StringGuid,[System.Management.Automation.PSReference]$ObjectGuid) # Returns True if successfully parsed
}

Call the method Test-IsGuid by passing the required GUID text to validate, the function returns True if the given input text is valid GUID, otherwise returns False.

# Check valid guid
Test-IsGuid 077e4982-4dd1-4d1f-ba18-d36e419971c1
# Check invalid guid string
Test-IsGuid 077e4982-4dd

Check a GUID is Empty or valid value

In .NET and PowerShell, Guid is a value type, so a variable of type Guid can’t be null. When you work with array of external objects which includes a property with guid type, some of the objects may contain the empty value in the guid property. In some cases, we need to find the objects with empty guid property to exclude or include those objects from further processing.

You can try the below commands to check the guid is empty or not.

#Check with empty guid
$StringGuid ="00000000-0000-0000-0000-000000000000"
$ObjectGuid = [System.Guid]::New($StringGuid)
$IsEmptyGUID = if($ObjectGuid -eq [System.Guid]::empty) {$true} Else {$False}
#Check with actual guid
$StringGuid ="077e4982-4dd1-4d1f-ba18-d36e419971c1"
$ObjectGuid = [System.Guid]::New($StringGuid)
$IsEmptyGUID = if($ObjectGuid -eq [System.Guid]::empty) {$true} Else {$False}

To check with an array of objects, you can check the property value is equal to or not equal to with [System.Guid]::empty in Where-Object.

$YourObjectArray | Where-Object { $_.YourGUIDProperty -eq [System.Guid]::empty }
#Or
$YourObjectArray | Where-Object { $_.YourGUIDProperty -ne [System.Guid]::empty }

Advertisement

Leave a Comment