# 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 = 'HistorianGateway'; $Kind = 'nssm' # nssm | svc $Drop = '^(Ldap__|Dashboard__GroupToRole__)' $Add = @('Ldap__Enabled=true', 'Ldap__Server=uswap-vdc-nam1.nam.zimmer.com', 'Ldap__Port=636', 'Ldap__Transport=Ldaps', 'Ldap__AllowInsecure=false', 'Ldap__FallbackServers__0=uswap-vdc-nam2.nam.zimmer.com:636', 'Ldap__SearchBase=DC=nam,DC=zimmer,DC=com', 'Ldap__ServiceAccountDn=svc_igntadmin@nam.zimmer.com', 'Ldap__ServiceAccountPassword=${secret:nam-ldap-svc-password}', 'Ldap__UserNameAttribute=sAMAccountName', 'Ldap__DisplayNameAttribute=name', 'Ldap__GroupAttribute=memberOf', 'Ldap__BindMode=ServiceAccount', 'Dashboard__GroupToRole__UG_WW_APP_ADMIN_QA=Administrator', 'Dashboard__GroupToRole__UG_WW_APP_IDE_RO_QA=Viewer', 'Dashboard__GroupToRole__UG_WW_HIST_ADMIN_QA=Administrator', 'Dashboard__GroupToRole__UG_WW_BTMGR_RO_QA=Viewer') $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" }