# Rewrite one service's env block (NSSM AppEnvironmentExtra or SCM Environment): drop entries whose NAME matches # $Drop, append $Add. Every other entry stays byte-identical (checked). No restart. Rendered per call. $ErrorActionPreference = 'Stop' $Svc = '__SVC__'; $Kind = '__KIND__' # nssm | svc $Drop = '__DROP__' $Add = @(__ADD__) $k = "HKLM:\SYSTEM\CurrentControlSet\Services\$Svc" if ($Kind -eq 'nssm') { $k = "$k\Parameters"; $prop = 'AppEnvironmentExtra' } else { $prop = 'Environment' } $before = @((Get-ItemProperty $k -Name $prop).$prop) $kept = @($before | Where-Object { $n = $_.Substring(0, [Math]::Max(0,$_.IndexOf('='))); $n -notmatch $Drop }) $dropped = @($before | Where-Object { $kept -notcontains $_ } | ForEach-Object { $_.Substring(0,$_.IndexOf('=')) }) foreach ($a in $Add) { $n = $a.Substring(0,$a.IndexOf('=')); if (@($kept | Where-Object { $_ -like "$n=*" }).Count) { throw "add collides with kept entry $n" } } $new = $kept + $Add Set-ItemProperty -Path $k -Name $prop -Value ([string[]]$new) -Type MultiString $after = @((Get-ItemProperty $k -Name $prop).$prop) if ($after.Count -ne $new.Count) { throw 'count mismatch after write' } for ($i = 0; $i -lt $new.Count; $i++) { if ($after[$i] -cne $new[$i]) { throw "entry $i differs after write" } } "$Svc ($prop) $($before.Count) -> $($after.Count) entries; dropped: $($dropped -join ', ')" foreach ($a in $Add) { " + $a" }