From 13f690362da48ee502d19a30a06501f456e0d367 Mon Sep 17 00:00:00 2001 From: Rain Sallow Date: Wed, 29 May 2024 17:09:41 -0400 Subject: [PATCH] (#310) Set-EnvironmentVariable: delete values properly We noticed over the last few days that the previous version of this code was *adding* blank values into the registry, which caused some issues with how environment variables are applied to new processes. Specifically, if a Machine-level variable is set, and a User-level variable by the same name is set to a blank value, new processes do not properly inherit the Machine-level value and it remains blank/unset. This change ensures that if someone sets an environment variable to a blank value, it will be properly *deleted* rather than set to a blank value. Additionally, a minor change has been made to Update-SessionEnvironment to ensure that if there are somehow blank values in the registry, it can sidestep those issues if it is called. --- .../Helpers/EnvironmentHelper.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Chocolatey.PowerShell/Helpers/EnvironmentHelper.cs b/src/Chocolatey.PowerShell/Helpers/EnvironmentHelper.cs index 468c7bb3b7..fedc3d86e2 100644 --- a/src/Chocolatey.PowerShell/Helpers/EnvironmentHelper.cs +++ b/src/Chocolatey.PowerShell/Helpers/EnvironmentHelper.cs @@ -166,7 +166,14 @@ public static void SetVariable(PSCmdlet cmdlet, string name, EnvironmentVariable cmdlet.WriteDebug($"Registry type for {name} is/will be {registryType}"); - registryKey.SetValue(name, value, registryType); + if (string.IsNullOrEmpty(value)) + { + registryKey.DeleteValue(name, throwOnMissingValue: false); + } + else + { + registryKey.SetValue(name, value, registryType); + } } try @@ -219,7 +226,10 @@ public static void UpdateSession(PSCmdlet cmdlet) foreach (var name in GetVariableNames(scope)) { var value = GetVariable(cmdlet, name, scope); - SetVariable(cmdlet, name, EnvironmentVariableTarget.Process, value); + if (!string.IsNullOrEmpty(value)) + { + SetVariable(cmdlet, name, EnvironmentVariableTarget.Process, value); + } } }