Modules/businessdev.ALbuild.Core/Public/Set-ALbuildConfig.ps1

function Set-ALbuildConfig {
    <#
    .SYNOPSIS
        Sets one or more ALbuild configuration values.
 
    .DESCRIPTION
        Applies overrides on top of the current configuration. By default the override lives for
        the session only; with -Persist the merged configuration is written to the config file so
        it survives future sessions.
 
    .PARAMETER Settings
        A hashtable of setting name/value pairs to apply.
 
    .PARAMETER Persist
        Persists the resulting configuration to the config file (Get-ALbuildConfigPath).
 
    .EXAMPLE
        Set-ALbuildConfig -Settings @{ ProcessRetryCount = 5; TelemetryEnabled = $true }
 
    .EXAMPLE
        Set-ALbuildConfig -Settings @{ ArtifactCacheFolder = 'D:\bcartifacts' } -Persist
 
    .OUTPUTS
        System.Collections.Specialized.OrderedDictionary (the updated configuration).
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param(
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNull()]
        [hashtable] $Settings,

        [switch] $Persist
    )

    if (-not $script:ALbuildConfigOverrides) {
        $script:ALbuildConfigOverrides = @{}
    }

    # Validate against the known settings before storing, so an invalid key never poisons state.
    $known = ([ALbuildConfig]::new()).Keys()
    foreach ($key in $Settings.Keys) {
        if ($known -notcontains $key) {
            throw "Unknown ALbuild configuration setting '$key'. Known settings: $($known -join ', ')."
        }
        $script:ALbuildConfigOverrides[$key] = $Settings[$key]
    }

    # Rebuild the cached effective config so callers see the change immediately.
    $effective = Get-ALbuildConfig -Refresh

    if ($Persist) {
        $configPath = Get-ALbuildConfigPath
        if ($PSCmdlet.ShouldProcess($configPath, 'Persist ALbuild configuration')) {
            try {
                $dir = Split-Path -Path $configPath -Parent
                if (-not (Test-Path -LiteralPath $dir)) {
                    New-Item -Path $dir -ItemType Directory -Force | Out-Null
                }
                ($effective.ToOrderedDictionary() | ConvertTo-Json -Depth 10) |
                    Set-Content -LiteralPath $configPath -Encoding UTF8
            }
            catch {
                throw "Failed to persist ALbuild configuration to '$configPath': $($_.Exception.Message)"
            }
        }
    }

    return $effective
}