Developer Lab · PowerShell
Generate UUID (GUID) in PowerShell
[System.Guid]::NewGuid() is built into .NET - zero dependencies, available in all PowerShell versions. Returns a Guid value type generated by the OS (UuidCreate on Windows).
Quick Reference
| Method | Output | Notes |
|---|---|---|
| [System.Guid]::NewGuid() | Guid object | Returns a Guid value type |
| [guid]::NewGuid().ToString() | String | Lowercase hyphenated string |
| .ToString("N") | String | 32 hex chars, no hyphens |
| .ToString("B") | String | With curly braces |
Primary Implementation
# Generate a GUID (UUID v4) - built-in .NET, zero dependencies
$guid = [System.Guid]::NewGuid()
Write-Output $guid
# → f47ac10b-58cc-4372-a567-0e02b2c3d479
# As a string (lowercase with hyphens - default)
$guidStr = [System.Guid]::NewGuid().ToString()
# Format specifiers
$guidD = [System.Guid]::NewGuid().ToString("D") # default: with hyphens
$guidN = [System.Guid]::NewGuid().ToString("N") # no hyphens (32 chars)
$guidB = [System.Guid]::NewGuid().ToString("B") # with braces
$guidP = [System.Guid]::NewGuid().ToString("P") # with parentheses
# Uppercase
$guidUpper = [System.Guid]::NewGuid().ToString().ToUpper()
# Assign to variable and use in string
$id = [System.Guid]::NewGuid().ToString()
Write-Output "Request ID: $id"
# Generate multiple GUIDs
$guids = 1..5 | ForEach-Object { [System.Guid]::NewGuid().ToString() }
$guids | ForEach-Object { Write-Output $_ }
# Validate a GUID string
function Test-Guid {
param([string]$Value)
$guid = [System.Guid]::Empty
return [System.Guid]::TryParse($Value, [ref]$guid)
}
Test-Guid "f47ac10b-58cc-4372-a567-0e02b2c3d479" # → True
Test-Guid "not-a-guid" # → FalseFormat Specifiers
All format options
$g = [System.Guid]::NewGuid()
$g.ToString() # "d" - f47ac10b-58cc-4372-a567-0e02b2c3d479
$g.ToString("N") # "n" - f47ac10b58cc4372a5670e02b2c3d479
$g.ToString("B") # "b" - {f47ac10b-58cc-4372-a567-0e02b2c3d479}
$g.ToString("P") # "p" - (f47ac10b-58cc-4372-a567-0e02b2c3d479)
$g.ToString("X") # "x" - {0xf47ac10b,0x58cc,0x4372,{0xa5,0x67,...}}New-Guid cmdlet (PowerShell 5+)
# PowerShell 5+ has a built-in cmdlet
$guid = New-Guid
Write-Output $guid # Guid object
Write-Output $guid.Guid # string property
Write-Output $guid.ToString() # same as .GuidReal-World Use Cases
1. Deployment script - unique build ID
$BuildId = [System.Guid]::NewGuid().ToString("N") # no hyphens
$DeployTime = (Get-Date).ToUniversalTime().ToString("o")
Write-Host "Starting deployment: $BuildId"
# Tag artifacts with the build ID
$artifactPath = ".\artifacts\build-$BuildId.zip"
Compress-Archive -Path ".\dist\*" -DestinationPath $artifactPath
# Write build metadata
@{
BuildId = $BuildId
DeployedAt = $DeployTime
Artifact = $artifactPath
} | ConvertTo-Json | Set-Content ".\build-info.json"
Write-Host "Build $BuildId packaged successfully"2. Azure REST API - idempotency key
$idempotencyKey = [System.Guid]::NewGuid().ToString()
$headers = @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
"x-ms-client-request-id" = $idempotencyKey
}
$body = @{
location = "eastus"
properties = @{ sku = "Standard_D2s_v3" }
} | ConvertTo-Json
Invoke-RestMethod `
-Uri "https://management.azure.com/subscriptions/$subId/resourceGroups/$rg/providers/..." `
-Method POST `
-Headers $headers `
-Body $body3. Unique temp file / directory
$jobId = [System.Guid]::NewGuid().ToString("N")
$workDir = Join-Path $env:TEMP "job-$jobId"
New-Item -ItemType Directory -Path $workDir | Out-Null
try {
Write-Host "Working in: $workDir"
# ... do work ...
} finally {
# Always clean up
Remove-Item -Recurse -Force $workDir -ErrorAction SilentlyContinue
Write-Host "Cleaned up $workDir"
}Common Mistakes
Using Get-Random for unique IDs
Get-Random is not CSPRNG-backed and only provides limited entropy. It is not suitable for unique identifiers. Always use [System.Guid]::NewGuid().
Comparing GUIDs as strings without normalizing case
GUID strings can be uppercase or lowercase depending on how they were generated. Always normalize to lowercase with .ToLower() or use [System.Guid]::Parse() for comparison, which is case-insensitive.
Not using TryParse for user-supplied GUIDs
[System.Guid]::Parse() throws an exception on invalid input. Use [System.Guid]::TryParse() for user-supplied values to avoid unhandled exceptions in scripts.
How It Works
[System.Guid]::NewGuid() calls the .NET runtime, which uses UuidCreate on Windows and a random source on Linux/macOS (PowerShell Core). It generates 16 bytes and sets the version (4) and variant bits; Microsoft does not document the result as cryptographically secure.
System.Guid is a 16-byte value type (struct) - stack-allocated, zero heap pressure. The ToString() call allocates a string.
Output Formats
ToString() / "D"
f47ac10b-58cc-4372-a567-0e02b2c3d479
"N" - no hyphens
f47ac10b58cc4372a5670e02b2c3d479
"B" - with braces
{f47ac10b-58cc-4372-a567-0e02b2c3d479}
Best Practices, Performance, and Security
Best practices
Use .ToString("N") for no-hyphen format in filenames and headers.
Use [System.Guid]::TryParse() for validating user-supplied GUIDs.
Use New-Guid cmdlet in PowerShell 5+ for cleaner syntax.
Performance
Very fast - .NET's Guid is a 16-byte value type with zero heap allocation. The ToString() call is the only allocation.
For bulk generation in scripts, use a pipeline: 1..1000 | ForEach-Object { [System.Guid]::NewGuid().ToString() }.
Security
Entropy source: the OS GUID generator - UuidCreate on Windows, a random source on Linux/macOS (PowerShell Core). Not documented as a CSPRNG.
Fine for deployment IDs and API idempotency keys. For session tokens or other secrets, use System.Security.Cryptography.RandomNumberGenerator.
Installation
UUID v4 (Guid.NewGuid)
# No installation needed
# System.Guid is part of .NET base class libraryAvailable in Windows PowerShell 2.0+, PowerShell Core 6+, and PowerShell 7+. Works on Windows, Linux, and macOS.
Frequently Asked Questions
How do I generate a UUID in PowerShell?
[System.Guid]::NewGuid() returns a random v4 GUID via .NET and works in every PowerShell version. Use .ToString() or the .Guid property for the string form, for example [guid]::NewGuid().ToString(). PowerShell 5+ also provides the New-Guid cmdlet, which wraps the same .NET API.
Is [guid]::NewGuid() cryptographically secure?
Not guaranteed. [guid]::NewGuid() produces a random v4 GUID via the OS GUID generator (UuidCreate on Windows), which Microsoft does not document as cryptographically secure. For session tokens, API keys, or other secrets, use System.Security.Cryptography.RandomNumberGenerator instead.
What is the difference between UUID v4 and v7 in PowerShell?
UUID v4 ([guid]::NewGuid() or equivalent) is fully random and not sortable. UUID v7 embeds a millisecond timestamp for chronological sorting (RFC 9562). Use v4 for general-purpose IDs; use v7 for database primary keys at scale.
Do I need to install a package for UUID generation in PowerShell?
No additional package is required for basic v4 generation in PowerShell. Check the Installation section for version-specific notes.
How do I validate a UUID string in PowerShell?
Use the platform's UUID parse/validation function, or test against the RFC 4122 regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. Always validate external input at API boundaries.
Should I use UUIDs as database primary keys in PowerShell applications?
UUIDs work well as primary keys for distributed systems. Prefer native UUID/BINARY(16) column types over VARCHAR(36). For very large tables, consider UUID v7 for better B-tree insert locality.
Can I generate UUIDs in PowerShell without a network connection?
Yes. UUID generation uses local OS entropy sources and does not require network access. Each call is independent and thread-safe on modern platforms.
What output formats are available in PowerShell?
The standard hyphenated lowercase string (36 chars) is the default. Most APIs also support 32-char hex (no hyphens) and 16-byte binary formats. Use string format for APIs and binary for database storage.
What RFC standards apply to PowerShell UUID generation?
Version 4 UUIDs follow RFC 4122. UUID v7 follows RFC 9562 (May 2024). Ensure your chosen method produces compliant version and variant bits.
When should I avoid UUID v1?
Avoid UUID v1 in security-sensitive contexts - it embeds MAC address and timestamp information. Prefer v4 ([guid]::NewGuid() or equivalent) unless you need legacy Cassandra timeuuid compatibility.
Key definitions
- UUID
- 128-bit universally unique identifier, usually shown as 36 hex characters with hyphens.
- CSPRNG
- Cryptographically secure pseudo-random number generator - the entropy source behind secure UUID generation.
- RFC 4122
- IETF standard defining UUID versions 1 through 5. Version 4 is random.
- RFC 9562
- IETF standard adding UUID versions 6, 7, and 8. Version 7 is time-ordered.