Skip to content

Read & Write Blank ("") Environment Variables #21186

Closed

Description

Summary of the new feature / enhancement

PowerShell cannot natively write nor read blank environment variables, although all major OSes (including Windows) and all other popular shells support blank environment variables.

Blank environment variables are occasionally (albeit unintuitively) used as flags for certain applications. PowerShell not natively1 listing these environment variables makes them effectively hidden from the user (meaning behavioral changes in downstream processes that cannot be explained by PowerShell's view of the environment variables). PowerShell not writing these environment variables means that a user cannot opt-in2 to behaviors triggered by them.

The reason for PowerShell's lack of support for blank environment variables seems to be due to a combination of historical lack of support in Windows3 and the current lack of support in .NET's System.Environment class4.

Proposed technical implementation details (optional)

No response

Footnotes

  1. PowerShell does display blank environment variables via [System.Environment]::GetEnvironmentVariables(…), but this lacks discoverability and is not documented for this use case in PowerShell. There is also zero reciprocal capability to create such environment variables. ↩

  2. Not idiomatically, anyway. When a downstream app recommends setting a blank environment variable for a particular use case, they tend to literally mean it must exist but also they reserve the right to have it support meaningful non-blank values in a future update. ↩

  3. As of Windows 7, cmd and PowerShell can set blank environment variables with setx - but this has usability limitations w.r.t. PowerShell workflows and does not apply to PowerShell outside of Windows. ↩

  4. System.Environment could be made to support blank environment variables - see https://github.com/dotnet/runtime/issues/50554. ↩

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Feb 5, 2024
  2. jhoneill commented on Feb 5, 2024

    @jhoneill

    all major OSes (including Windows) and all other popular shells support blank environment variables.

    Really ?
    image

    SET in cmd can't create a blank variable, setting one to blank deletes it.

    image

    And set via the GUI to persist variables in the registry won't allow a blank value to be saved.

    Blank environment variables are occasionally (albeit unintuitively) used as flags for certain applications.

    If you can cite an example of one where environment variable present, and blank means something different to not present it would expand my experience.

  3. 237dmitry commented on Feb 5, 2024

    @237dmitry

    Read & Write Blank ("")

    If you mean double quotes:

    cmd.exe

    > set blank=""
    > set blank
    blank=""
    

    pwsh.exe

    $ [environment]::SetEnvironmentVariable('blank','""',0)
    $ gi env:blank
    
    Name                           Value
    ----                           -----
    blank                          ""
    
  4. jborean93 commented on Feb 5, 2024

    @jborean93
    Collaborator

    Really ?

    James O'Neill (@jhoneill) yes, on non-Windows you can set an env var to an empty string, it's only Windows that doesn't support empty strings. It might technically be possible to do on Windows by manually editing the env block but it's not easily done using the public APIs. In any case it's certainly possible on Linux and macOS.

    image

    Bruce Markham (@brucificus) while this would be great to have unfortunately dotnet currently doesn't allow such a thing, it treats an empty string with the SetEnvironmentVariable as a way to unset an env var as per legacy behaviour with Windows. The issue in dotnet is tracked with dotnet/runtime#50554 and a duplicate issue dotnet/runtime#95559.

    Until dotnet can do this PowerShell cannot do anything about it short of an ugly hack which will probably cause more problems than it solves.

  5. brucificus commented on Feb 6, 2024

    @brucificus
    Author

    James O'Neill (@jhoneill) and Jordan Borean (@jborean93), re: Windows support…

    As of the inclusion of setx in Windows 7, Windows supports blank environment variables.

    To set one yourself:

    C:\Users\Bruce>setx A ""
    
    SUCCESS: Specified value was saved.
    
    C:\Users\Bruce>pwsh -NoLogo -NoProfile -Command "[System.Environment]::GetEnvironmentVariables([EnvironmentVariableTarget]::User).ContainsKey('A')"
    True
    
    C:\Users\Bruce>pwsh -NoLogo -NoProfile -Command "[System.Environment]::GetEnvironmentVariables([EnvironmentVariableTarget]::User)['A']"
    
    
    
  6. brucificus commented on Feb 6, 2024

    @brucificus
    Author

    rhubarb-geek-nz and James O'Neill (@jhoneill), re: examples of semantically "meaningfully" blank environment variables…

    …here are some examples I've run into from "the wild":

    • VSCODE_GIT_EDITOR_EXTRA_ARGS1
    • DOCKER_TLS_VERIFY2
    • NO_COLOR3 (for practicality reasons, YMMV, see footnote)

    There is also the (meta-)use-case of writing cross-platform PowerShell code that manipulates (or validates) environment variables "in bulk"4 - while handling blank values correctly, (as possibly motivated by either shell customization reasons or system administration reasons). Don't forget unit-tests of such code, too - such as in Pester - which would necessitate emulating these circumstances.

    Footnotes

    1. I haven't found a canonical rationale for why VSCode would set this to be empty, but it does sometimes. (The closest clue I found is https://github.com/microsoft/vscode/issues/137183.) ↩

    2. https://docs.docker.com/engine/reference/commandline/cli/ ↩

    3. https://no-color.org/ indeed has verbiage explicitly declaring that a blank NO_COLOR is semantically equivalent to not existing, but it isn't consistently followed. ↩

    4. I know this one seems particularly esoteric, but it's what got me here, specifically with respect to the other examples I mentioned. Third-party tools can care about the difference between blank vs. unset. If we want to be able to write PowerShell code that wraps/tests such tools, the language needs better support for blank environment variables. ↩

  7. mklement0 commented on Feb 6, 2024

    @mklement0
    Contributor

    As for the technical part of the debate, to add to Jordan Borean (@jborean93)'s comment:

    • At the platform-native system call level, both Windows and Unix-like platforms do support setting value-less env. vars., albeit only in-process (SetEnvironmentVariable() / setenv())

    • However, persisting a value-less environment variable does not work (properly) on Windows (on Unix, the .NET APIs - for good reasons, due to lack of standardized support - fundamentally do not support persistent updates, and neither do the platform-native system calls):

      • The fact that setx A "" is even accepted should be considered a setx.exe bug, because such variables do not surface as process environment variables.

      • The fact that [System.Environment]::GetEnvironmentVariables([EnvironmentVariableTarget]::User).ContainsKey('A') surfaces such a variable is an .NET API artifact and arguably also a bug:

        • Of necessity, .NET directly reads the registry-based definitions of environment variables and reports them as such, irrespective of their (non-)value, not realizing that processes will not see variables based on an empty REG_SZ (or REG_EXPAND_SZ) value.
    • There is no good reason (and there never was, even in the Windows-only .NET Framework days) for .NET APIs to make the platform-native ability to define value-less environment variables inaccessible, and the current conflation of both null and the empty string as a signal to remove an env. var. was never justified.

    Update: See below for potential solutions.

  8. brucificus commented on Feb 7, 2024

    @brucificus
    Author

    rhubarb-geek-nz and Michael Klement (@mklement0), I mostly agree am sympathetic to the idea that blank environment variables are unwise to create/expect. That's not particularly germane to my specific ask, though.

    It is currently impossible to write an idiomatic PowerShell script that can reliably serve as either an arbiter or an auditor of environment variables when they are flowing from an upstream process to a downstream one. Blank environment variables do exist; they'll never be eradicated and are likely to increase in prevalence over time. It is painful that PowerShell chokes on these when other shells do not.

  9. mklement0 commented on Feb 7, 2024

    @mklement0
    Contributor

    Bruce Markham (@brucificus):

    • Not only do I agree that .NET / PowerShell should indeed support creating empty-string environment variables, I don't think it is an unwise practice, given that it is well-established on Unix-like platforms, and given how easy POSIX-like shells make it to define such variables.

      • E.g., NO_COLOR= pwsh -c '$PSStyle.OutputRendering' defines NO_COLOR in a process-scoped manner without a value (with the empty string as the value; to be more explicit, NO_COLOR='' ... would work too).
      • As an aside:
        • The fact that PowerShell then outputs PlainText indicates that it truly only cares about the existence of the variable, whatever its value.
        • This technically contradicts the https://no-color.org/ specification, as you note, but I think the latter is at fault here: to align with common practice, it should not stipulate the presence of a non-empty value (not only does it not align with common practice, it is also a useless restriction).
    • The inability to set empty variables is especially problematic in code that methodically saves and restores existing environment variables (perhaps that's what you meant by "bulk" handling), as doing so can end up accidentally removing variables; I've left a comment at Environment.SetEnvironmentVariable does not support setting empty values dotnet/runtime#50554 (comment) to that effect.

    • As an aside re Windows:

      • That the SetEnvironmentValue() WinAPI function permits creating empty environment variable values may be more of an accident than by deliberate design (yet there's still no good reason for .NET / PowerShell to prevent it), given the inability to persist such variables, and given GetEnvironmentValue()'s return value: it returns the count of characters copied (excluding the null terminator) in the success case and 0 in case of failure. However, given that an empty variable legitimately copes 0 characters, you have to go out of your way to distinguish between a non-existent and an empty variable, as demonstrated below. Fortunately, this distinction is much easer in .NET / PowerShell: a non-existent variable reports $null, whereas an empty one reports '' (empty string).

    As for possible solutions:

    • Changing the behavior of $env:NO_VALUE = ... to distinguish between '' (define, with an empty value) and $null (remove) is likely too breaking a change, and the same goes for the underlying .NET API, Environment.SetEnvironmentVariable()
    • Therefore, a new Environment.SetEnvironmentVariable() overload is the likeliest resolution, as discussed in Environment.SetEnvironmentVariable does not support setting empty values dotnet/runtime#50554 - assuming that the .NET team decides this change is worth making.
      • This is certainly to be hoped for, given that there is currently no workaround available on Unix (see below).
    • Asking PowerShell users to directly call .NET APIs for such basic functionality would be unreasonable, so this new functionality could be surfaced via a dynamic Set-Item (possibly also: Set-Content) switch named, say, -AllowEmptyString; e.g.:
    • Conceivably (and additionally) an opt-in preference variable could be introduced that changes the behavior of $env:NO_VALUE = ... as described above; however, given PowerShell's dynamic scoping, this variable (as any preference variable) needs to managed carefully to avoid affecting code that expects the current behavior.
    # WISHFUL THINKING, requires implementation of support in .NET first
    
    Set-Item -AllowEmptyString NO_VALUE  # -Value argument optional in this case.
    
    # For the scenario of restoring previous values.
    Set-Item -AllowEmptyString $savedVarName $savedVarValue

    The following cross-platform code demonstrates that getting empty environment variables already works fine, and that
    on Windows you can work around the current inability to create (set) such variables via a P/Invoke call to the SetEnvironmentVariable() WinAPI function.
    Sadly, an analogous workaround via setenv() does not work on Unix-like platforms, because native libraries cannot modify a managed caller's environment there (see this Stack Overflow answer for background).

    # The script block that examines the empty environment variable, once defined,
    # as well as a non-existing one for contrast.
    $sb = {
      [pscustomobject] @{
        'Item Env:NOVALUE exists?'                                                            = Test-Path Env:NOVALUE
        '$env:NOVALUE is empty string (not $null)?'                                           = $env:NOVALUE -is [string] -and $env:NOVALUE -eq ''
        'Nonexistent $env:NOSUCHVAR is $null?'                                                = $null -eq $env:NOSUCHVAR
        '.NET: [Environment]::GetEnvironmentVariables() contains NOVALUE?'                    = [Environment]::GetEnvironmentVariables().Contains('NOVALUE')
        '.NET: [Environment]::GetEnvironmentVariable("NOVALUE") is empty string (not $null)?' = [Environment]::GetEnvironmentVariable('NOVALUE') -is [string] -and [Environment]::GetEnvironmentVariable('NOVALUE') -eq ''
        '.NET: Nonexistent [Environment]::GetEnvironmentVariable("NOSUCHVAR") is $null?'      = $null -eq [Environment]::GetEnvironmentVariable('NOSUCHVAR')
      }
    }
    
    if ($IsWindows) {
      # Compile a helper type that calls the WinAPI, which *does* allow setting no-value
      # env. vars.
      Add-Type -Namespace Demo -Name WinApiHelper -UsingNamespace System.Text -MemberDefinition @'
        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern bool SetEnvironmentVariable(string lpName, string lpValue);
    
        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern UInt32 GetEnvironmentVariable(string lpName, StringBuilder lpBuffer, UInt32 nSize);
    
        [DllImport("kernel32")]
        static extern void SetLastError(UInt32 dwErrCode);
    
        public static void SetEnvVar(string name, object value) 
        {
            if (! SetEnvironmentVariable(name, (string)value))
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastSystemError());
            }
        }
    
        public static string GetEnvVar(string name) 
        {
            var sb = new StringBuilder(32767);
            int lastErr;
            SetLastError(0);
            GetEnvironmentVariable(name, sb, (UInt32) (sb.Capacity + 1));
            lastErr = Marshal.GetLastSystemError();
            if (lastErr != 0) 
            {
                throw new System.ComponentModel.Win32Exception(lastErr);
            }
            return sb.ToString();
        }
    '@
    
      [Demo.WinApiHelper]::SetEnvVar('NOVALUE', '')
    
      & $sb
    
    }
    else {
    
      # Use sh -c to create a no-value env. var. and invoke a PowerShell child process
      # to examine it.
      $encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($sb))
      sh -c ('NOVALUE= pwsh -NoProfile -EncodedCommand ' + $encodedCommand)
    }
  10. rhubarb-geek-nz commented on Feb 7, 2024

    @rhubarb-geek-nz
    • E.g., NO_COLOR= pwsh -c '$PSStyle.OutputRendering' defines NO_COLOR in a process-scoped manner without a value (with the empty string as the value; to be more explicit, NO_COLOR='' ... would work too).

    Except that is not the definition of NO_COLOR, you can do what you like but that does not mean anybody else should abide by it. Typically in shell script you might use test -n "$NO_COLOR" and that will return false as NO_COLOR not being present according to the specification.

    So "would work too" is not true.

    $ NO_COLOR= sh -c 'set | grep NO_COLOR; if test -z "$NO_COLOR"; then echo you can use color; fi'
    NO_COLOR=''
    you can use color
    
  11. mklement0 commented on Feb 7, 2024

    @mklement0
    Contributor

    rhubarb-geek-nz, I don't understand your comment; my point was that
    NO_COLOR= pwsh -c '$PSStyle.OutputRendering' and
    NO_COLOR='' pwsh -c '$PSStyle.OutputRendering' are equivalent in POSIX-compatible shells, and define environment variable NO_COLOR with an empty value exclusively for the utility call (pwsh) at hand.

    Similarly,
    export NO_COLOR= and
    export NO_COLOR='' are equivalent, and define the environment variable for the current process.

    Whether or not NO_COLOR should be honored if it exists but has an empty value is incidental to the issue at hand; if you feel strongly that PowerShell should follow the letter of the no-color.org spec, I suggest creating a new issue.
    Update: I have since done so myself:

  12. mklement0 commented on Feb 7, 2024

    @mklement0
    Contributor

    P.S., rhubarb-geek-nz:

    • It isn't typically shell code that abstractly tests for the mere existence of an environment variable, it is utilities (external executables), which on Unix is simple as int isDefined = NULL != getenv("SOME_ENV_VAR");
      • If you do need it in shell code: While it is true that -n and -z tests do not allow you test variable existence, parameter expansion offers a workaround; e.g.:
    # From a POSIX-compatible shell
    
    # Create, but with an empty value.
    export NO_COLOR=
    
    # Detect whether the variable exists, whether empty or not.
    [ 'defined' = "${NO_COLOR+defined}" ] && echo DEFINED || echo UNDEFINED
    • The very fact that the the no-color.org spec. explicitly prescribes the behavior in the empty-value case indicates that such environment variables are used, and, in fact, the distinction can serve a useful purpose (unlike what I originally thought):

      • An invocation such as NO_COLOR= foo ... from a POSIX-like shell is then a convenient way to ad hoc opt out of a an ambient non-empty definition of this variable. That is, you can use this if you know that you do want color, and don't want to have to rely on the current state of the process' environment to not have NO_COLOR defined (with a non-empty value).
    # From a POSIX-compatible shell
    
    export NO_COLOR=1 
    
    foo --bar  # NO_COLOR is in effect
    
    NO_COLOR= foo --bar # Deactivate NO_COLOR for this call

    It is unfortunate that PowerShell doesn't have similarly concise syntax for child process-scoped environment-variable definitions; adding support for it is the subject of:

  13. mklement0 commented on Jun 18, 2024

    @mklement0
    Contributor

    .NET runtime PR #103551 - which I will land in .NET 9 (preview 6), which will affect PowerShell 7.5 - just implemented a breaking change to allow setting empty(-string) environment variables, in-process only (emphasis added):

    • This change updates Environment.SetEnvironment to treat empty string value as empty string value (null value is still treated as request to delete the environment variable).
    • [...] updates ProcessStartInfo.Environment to treat null vs. empty string the same way as Environment.SetEnvironment for consistency.

    Since PowerShell mediates access to this API via its $env:FOO = ... syntax, it could technically opt-out of this change for the sake of backward compatibility (which I personally wouldn't recommend).
    Whatever path is chosen must be carefully considered.

  14. added
    WG-Engine
    on Jun 19, 2024
  15. 6 remaining items

  16. JamesWTruher commented on Aug 5, 2024

    @JamesWTruher
    Collaborator

    The WG discussed this and believe the fundamental issue is being addressed within the dotnet framework. When we take the version of dotnet which has this (dotnet/runtime#50554) then we'll need to be sure that we enable this in pwsh. We also concluded that while this is a breaking change, it will welcome. We're not yet sure if this will just start working, or whether we will need to make adjustments in pwsh, but we agree that providing an environment variable without a value is a useful behavior.

  17. added
    WG-Reviewed
    Waiting - DotNetCore
    and removed
    WG-NeedsReview
    Needs-Triage
    on Aug 5, 2024
  18. EliahKagan commented on Feb 9, 2025

    @EliahKagan

    Since PowerShell 7.5.0 (released a couple weeks ago), as predicted in #21186 (comment), $env:FOO = $null and $env:FOO = '' differ as described in #21186 (comment), with $null continuing to unset the variable but '' setting a literal empty string as the value.

  19. added
    Resolution-No Activity
    on Aug 8, 2025
  20. microsoft-github-policy-service commented on Aug 8, 2025

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if there is no further activity in 7 days, the issue will be closed automatically.

    Activity in this case refers only to comments on the issue. If the issue is closed and you are the author, you can re-open the issue using the button below. Please add more information to be considered during retriage. If you are not the author but the issue is impacting you after it has been closed, please submit a new issue with updated details and a link to this issue and the original.

  21. 0009-0009-1013-986X commented on Aug 16, 2025

    @0009-0009-1013-986X
  22. mklement0 commented on Aug 16, 2025

    @mklement0
    Contributor

    dotnet/runtime#103551 fixed the issue on the .NET side in .NET 9, and PowerShell 7.5+ implicitly surfaces this fix, so this issue is effectively resolved.

    Remove-Item Env:FOO -ErrorAction Ignore
    
    $null -eq $env:FOO  # always $true
    
    # PS 7.5+ / .NET 9+ only:
    # Define empty var.
    $env:FOO = ''
    
    # Verify that the var. exists and contains the empty string.
    $env:FOO.GetType().Name
    Get-Item Env:FOO
    
    Remove-Item Env:FOO
  23. added
    Resolution-Fixed
    Resolution-External
    and removed
    Resolution-No Activity
    on Mar 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Breaking-ChangeIssue-EnhancementResolution-ExternalResolution-FixedWG-EngineWG-ReviewedWaiting - DotNetCore

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions