Scanning database...
Tools
Articles

No matches found for ""

View All Results
Home Dev Lab powershell
Developer Lab

UUID in PowerShell

Production-ready implementation guide with CSPRNG-backed code snippets.



Generate UUID (GUID) in PowerShell

[System.Guid]::NewGuid() is built into .NET — zero dependencies, available in all PowerShell versions. Returns a Guid value type backed by BCryptGenRandom 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

Production Ready
powershell snippet
# 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"                              # → False

Format Specifiers

All format options

powershell snippet
$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 snippet
# 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 .Guid

Real-World Use Cases

1. Deployment script — unique build ID

powershell snippet
$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

powershell snippet
$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 $body

3. Unique temp file / directory

powershell snippet
$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 BCryptGenRandom on Windows and /dev/urandom on Linux/macOS (PowerShell Core). It generates 16 random bytes and sets the version (4) and variant bits.

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

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() }.

Installation

# No installation needed
# System.Guid is part of .NET base class library

Available in Windows PowerShell 2.0+, PowerShell Core 6+, and PowerShell 7+. Works on Windows, Linux, and macOS.

Security

Entropy source: BCryptGenRandom on Windows, /dev/urandom on Linux/macOS (PowerShell Core). Cryptographically secure.

Suitable for deployment IDs, API idempotency keys, and session tokens in automation scripts.