Skip to content

get-childitem env: fails on Windows when an environment variable is defined twice, cased differently #6305

@ericsciple

Description

@ericsciple

The problem:
get-childitem env: fails on Windows when an environment variable exists twice, each instance cased differently.

The scenario:
On Windows, set the environment variable NPM_CONFIG_PATH to control where the npm cache is created. And use npm to run unit tests, use powershell within a unit test, and from powershell invoke get-childitem env:. Note, it is common to use npm test to build and test a nodejs project.

It appears npm internally creates environment variables to manage state, and a lower-case variable npm_config_path is created. When powershell is invoked from the unit test, the environment variables NPM_CONFIG_PATH and npm_config_path are both set.

Steps to reproduce

On Windows, tested with npm v5.6.0 in my PATH.

Write-Host "******************** SETTING NPM_CONFIG_PATH ********************"
$null = mkdir env-test
cd env-test
$env:NPM_CONFIG_PATH = $PWD
Write-Host "******************** CREATING PACKAGE.JSON ********************"
& npm init --force --yes
Write-Host "******************** MODIFYING PACKAGE.JSON ********************"
$package = Get-Content package.json | ConvertFrom-Json
$package.scripts.test = "pwsh -command Get-ChildItem env:"
Set-Content -LiteralPath package.json -Encoding UTF8 -Value (ConvertTo-Json -InputObject $package -Depth 99)
Get-Content package.json
Write-Host "******************** TESTING ENV PS DRIVE, VIA NPM ********************"
& npm test

Expected behavior

PowerShell should gracefully handle the duplicate environment variable. The set builtin in cmd.exe handles it gracefully. .NET Environment.GetEnvironmentVariables() handles it gracefully.

Actual behavior

Get-ChildItem fails with "An item with the same key has already been added. Key: NPM_CONFIG_PATH"

Environment data

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      6.0.1
PSEdition                      Core
GitCommitId                    v6.0.1
OS                             Microsoft Windows 10.0.16299
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions