Skip to content

Passing $null to [Environment]::SetEnvironmentVariable sets environment variable to empty string '' (7.5 RC1) #24637

Closed

Description

@pjking07

Prerequisites

Steps to reproduce

In .NET 9, a breaking change introduced empty string support to environment variables. As of that change, the only way to remove an environment variable is to set it to null via Environment.SetEnvironmentVariable(). I've confirmed this behavior in .NET 9 with C#.

PR #24133 introduced .NET 9, and the above breaking change, into PowerShell v7.5.0-preview.4.

However, setting an environment variable to $null in [Environment]::SetEnvironmentVariable() now sets the environment variable to an empty string, instead of the expected behavior of unsetting the environment variable. Notably, setting the variable to null via the ENV provider works as expected.

The below tests explain the expected behavior, but Environment Variable.System.Environment.Should unset environment variables with null fails because [Environment]::GetEnvironmentVariable() yields an empty string '' instead of $null.

Describe 'Environment Variable' {

    Context 'System.Environment' {
        It 'Should unset environment variables with null' {
            [System.Environment]::SetEnvironmentVariable('TEST_DOTNETAPI_NULL', $null)
            [System.Environment]::GetEnvironmentVariable('TEST_DOTNETAPI_NULL') | Should -Be $null
        }

        # See breaking change in .NET 9:
        # https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/9.0/empty-env-variable
        It 'Should set environment variables with empty string' -Skip:([Environment]::Version.Major -lt 9) {
            [System.Environment]::SetEnvironmentVariable('TEST_DOTNETAPI_EMPTY', '')
            [System.Environment]::GetEnvironmentVariable('TEST_DOTNETAPI_EMPTY') | Should -Be ''
        }
    }

    Context 'ENV Drive' {
        It 'Should unset environment variables with null' {
            $ENV:TEST_ENV_NULL = $null
            $ENV:TEST_ENV_NULL | Should -Be $null
        }

        # See breaking change in .NET 9:
        # https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/9.0/empty-env-variable
        It 'Should set environment variables with empty string' -Skip:([Environment]::Version.Major -lt 9) {
            $ENV:TEST_ENV_EMPTY = ''
            $ENV:TEST_ENV_EMPTY | Should -Be ''
        }
    }
}

Expected behavior

All four tests pass

Actual behavior

> Invoke-Pester .\EnvironmentVariable.Tests.ps1

Starting discovery in 1 files.
Discovery found 4 tests in 7ms.
Running tests.
[-] Environment Variable.System.Environment.Should unset environment variables with null 4ms (3ms|0ms)
 Expected $null, but got <empty>.
 at [System.Environment]::GetEnvironmentVariable('TEST_DOTNETAPI_NULL') | Should -Be $null, C:\EnvironmentVariableTest\EnvironmentVariable.Tests.ps1:6
 at <ScriptBlock>, C:\EnvironmentVariableTest\EnvironmentVariable.Tests.ps1:6
Tests completed in 60ms
Tests Passed: 3, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0

Error details

No response

Environment data

Name                           Value
----                           -----
PSVersion                      7.5.0-rc.1
PSEdition                      Core
GitCommitId                    7.5.0-rc.1
OS                             Microsoft Windows 10.0.22631
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Dec 3, 2024
  2. changed the title [-]Passing `$null` to `[Environment]::SetEnvironmentVariable` no longer unsets environment variables (7.5 RC1)[/-] [+]Passing `$null` to `[Environment]::SetEnvironmentVariable` sets environment variable to empty string `''` (7.5 RC1)[/+] on Dec 3, 2024
  3. pjking07 commented on Dec 3, 2024

    @pjking07
    Author

    I believe this is related to parameter parsing for dotnet methods, in which null string values seem to coalesce to an empty string "".

    As an example, let's use .NET string compare between null and an empty string in both PowerShell and C#. We'll find that PowerShell finds them equal while C# finds them different.

    [string]::Compare($null, '') # 0
    string.Compare(null, "") // -1
  4. rhubarb-geek-nz commented on Dec 3, 2024

    @rhubarb-geek-nz

    See #24605

    GitHub
    The following code produces different results in 7.4.6 and 7.5-rc1. This breaks some things. Is this a feature to stay or a bug to fix? $name = 'TEST_VAR2' $value = $null [Environment]::SetEnvironm...
  5. kilasuit commented on Dec 3, 2024

    @kilasuit
    Collaborator

    I think that this is similar to the discussion that was had in Issue 21186 & the output from the Working Group in this comment

  6. mklement0 commented on Dec 3, 2024

    @mklement0
    Contributor

    Thanks, Ryan Yates (@kilasuit).

    Indeed, this was an intentional breaking change in .NET 9, which the working group in effect decided to surface in PowerShell too:

    To recap, based on #21186 (comment):

    • [As before] $env:FOO = $null will remove the variable.

    • [Breaking change] $env:FOO = '' will now create it as / set it to the empty string.

    • [Newly introduced bug] Set-Content Env:FOO -Value $null converts $null to the empty string (due the parameter binding turning the $null into an empty array, which is then stringified to the empty string), so it will no longer remove the variable.

      • By contrast, Set-Item Env:FOO ... behaves the same as namespace variable notation ($env:FOO = ...)
  7. microsoft-github-policy-service commented on Dec 5, 2024

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as duplicate and has not had any activity for 1 day. It has been closed for housekeeping purposes.

  8. microsoft-github-policy-service commented on Dec 5, 2024

    @microsoft-github-policy-service
    Contributor

    📣 Hey PJ King (@pjking07), how did we do? We would love to hear your feedback with the link below! 🗣️

    🔗 https://aka.ms/PSRepoFeedback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs-TriageResolution-Duplicate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions