Skip to content

Commit

Permalink
(chocolatey#310) Set-EnvironmentVariable: delete values properly
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
vexx32 committed May 30, 2024
1 parent 5c82bf0 commit 73d1ab3
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/Chocolatey.PowerShell/Helpers/EnvironmentHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
}
}

Expand Down

0 comments on commit 73d1ab3

Please sign in to comment.