private/Software/Update-OSDeploySessionEnvironment.ps1
|
<#
.SYNOPSIS Refreshes the current PowerShell session's environment variables from the Machine and User registry scopes. .DESCRIPTION After installing software, the current session's environment is stale because the installer wrote new registry values (PATH entries, etc.) that are not reflected in the running process until a new session is started. This function reads every environment variable from HKLM and HKCU and applies them to the current Process scope, then rebuilds $env:Path as the concatenation of Machine Path and User Path — the same merge Windows performs for new shells. .NOTES Author: David Segura Company: Recast Software Change Summary: #> function Update-OSDeploySessionEnvironment { [CmdletBinding()] param () Write-Host "[$(Get-Date -format s)] [$($MyInvocation.MyCommand.Name)] Refreshing session environment variables..." -ForegroundColor DarkGray # Machine scope first so User-scope values take precedence for non-Path vars foreach ($scope in @('Machine', 'User')) { $vars = [System.Environment]::GetEnvironmentVariables($scope) foreach ($key in $vars.Keys) { if ($key -ne 'Path') { [System.Environment]::SetEnvironmentVariable($key, $vars[$key], 'Process') } } } # Rebuild Path as Machine + User (matches standard Windows PATH merge behaviour) $machinePath = [System.Environment]::GetEnvironmentVariable('Path', 'Machine') $userPath = [System.Environment]::GetEnvironmentVariable('Path', 'User') $env:Path = (@($machinePath, $userPath) | Where-Object { -not [string]::IsNullOrEmpty($_) }) -join ';' Write-Host "[$(Get-Date -format s)] [$($MyInvocation.MyCommand.Name)] Session environment variables refreshed." -ForegroundColor Green } |