private/BootMedia/Steps/Step-BootImageSetEnvVars.ps1

#Requires -PSEdition Core

function Step-BootImageSetEnvVars {
    <#
    .SYNOPSIS
        Sets environment variables in the mounted WinPE image SYSTEM hive.
 
    .NOTES
        Author: David Segura
        Version: 0.1.0
    #>

    [CmdletBinding()]
    param ()

    $MountPath = $global:BuildMedia.MountPath

    # Build the env var table: static entries from module.json + dynamic OSDEPLOY_VERSION
    $envVars = [ordered]@{}

    $envConfig = $global:OSDeployModule.BootImage.env
    if ($envConfig) {
        foreach ($prop in $envConfig.PSObject.Properties) {
            $envVars[$prop.Name] = $prop.Value
        }
    }

    $moduleVersion = Get-OSDeployModuleVersion
    if ($moduleVersion) {
        $envVars['OSDEPLOY_VERSION'] = $moduleVersion.ToString()
    }

    if ($envVars.Count -eq 0) {
        Write-OSDeployCoreProgress 'No environment variables to set in WinPE — skipping'
        return
    }

    Write-OSDeployCoreProgress 'Setting environment variables in WinPE SYSTEM hive'

    $systemHivePath = Join-Path $MountPath 'Windows\System32\Config\SYSTEM'
    if (-not (Test-Path $systemHivePath)) {
        Write-Warning "SYSTEM hive not found at $systemHivePath"
        return
    }

    $hiveName = 'OSDeployCoreMounted'
    try {
        reg.exe LOAD "HKLM\$hiveName" "$systemHivePath" 2>&1 | Out-Null

        $regPath = "HKLM:\$hiveName\ControlSet001\Control\Session Manager\Environment"
        if (-not (Test-Path $regPath)) {
            New-Item -Path $regPath -Force | Out-Null
        }

        foreach ($key in $envVars.Keys) {
            Write-Host -ForegroundColor Gray " $key = $($envVars[$key])"
            Set-ItemProperty -Path $regPath -Name $key -Value $envVars[$key] -Type String
        }
    }
    finally {
        Start-Sleep -Seconds 3
        reg.exe UNLOAD "HKLM\$hiveName" 2>&1 | Out-Null
    }
}