Home ยป PowerShell ยป PowerShell Convert Guid to String

PowerShell Convert Guid to String

PowerShell .Net framework provides Guid class that represents a GUID and ToString() method to convert guide to string in PowerShell. It returns the string representation of the GUID.

GUID is a unique identifier that consists of 32 hexadecimal digits, divided into 5 groups ( 8,4,4,4,412) separated by hyphens. For example, d5f7e40d-e8d6-480e-afa9-b591ad942c48

In this article, we will discuss how to use the ToString() method of the GUID class in PowerShell to convert guid to string.

Convert Guid to String in PowerShell

Use Guid class available in the PowerShell .Net framework to create, and format guid in PowerShell. It has ToString() method that converts guid to string in PowerShell.

# Create a guid in PowerShell
$guid = [guid]::NewGuid()

# Convert guid to string in PowerShell
$sGuid = $guid.ToString()

In the above PowerShell script, guid class has the NewGuid() method that creates a unique identifier of 32 hexadecimal digits guid and stores it in the variable $guid.

To convert guid to string in PowerShell, it uses the ToString() method of guid class and returns the string representation of the guid.

The output of the above PowerShell script is:

PowerShell Convert Guid to String
PowerShell Convert Guid to String

Another simple way to create a guid and convert it into a string in PowerShell is:

$strGuid = [guid]::NewGuid().ToString()
Write-Host $strGuid

The above PowerShell one-liner script uses guid class that provides NewGuid() method to create a guid and ToString() method to convert a guid to a string.

The output of the above PowerShell script prints the string representation of the guid.

PS C:\> $strGuid = [guid]::NewGuid().ToString()
PS C:\> $strGuid
1c3b6d41-aa17-4fe8-ac6d-b3992522789a
PS C:\>

Cool Tip: How to convert byte array to string in PowerShell!

PowerShell New Guid to String

Guid class provides methods and properties to work with GUID. It has a Guid property that gets the guid as a string only.

 [guid]::NewGuid().Guid 

In the above PowerShell script, NewGuid() method generates Guid and then uses the Guid property to get a string representation of new guid.

The output of the above PowerShell script for new guid to string is:

PS C:\> [guid]::NewGuid().Guid                                          
06444a11-2dbd-4597-800b-1c1b20ed4bd3

Cool Tip: How to convert string to guid in PowerShell!

Conclusion

I hope the above article on how to use the ToString() method of guid class to convert guid to string is helpful to you.

We have learned how to use the PowerShell .Net framework that provides a GUID class to create a new guid using NewGuid() method and ToString() method to convert guid to string.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.