Load and Validate Environment Config in PowerShell

PowerShell
function Get-EnvConfig {
    param([Parameter(Mandatory)][hashtable]$Schema)
    $config = @{}
    foreach ($name in $Schema.Keys) {
        $spec = $Schema[$name]
        $raw = [Environment]::GetEnvironmentVariable($name)
        if ([string]::IsNullOrWhiteSpace($raw)) {
            if ($spec.Required) { throw "Missing required environment variable '$name'." }
            $config[$name] = $spec.Default
            continue
        }
        if ($spec.Validate -and -not (& $spec.Validate $raw)) {
            throw "Invalid value for '$name': '$raw'."
        }
        $config[$name] = $raw
    }
    [pscustomobject]$config
}