@@ -57,8 +57,19 @@ function Invoke-Test {
5757
5858# Record the original environment variables.
5959$originalEnv = @ { }
60- foreach ($envVar in (Get-ChildItem - LiteralPath env:)) {
61- $originalEnv [$envVar.Name ] = $envVar.Value
60+ foreach ($key in ([Environment ]::GetEnvironmentVariables()).Keys) {
61+ if (! $originalEnv.ContainsKey ($key )) {
62+ $value = [Environment ]::GetEnvironmentVariable($key )
63+ $originalEnv [$key ] = " $value "
64+ } else {
65+ # NPM on Windows is somehow able to create a duplicate environment variable cased differently.
66+ # For example, if the environment variable NPM_CONFIG_CACHE is defined, npm test is somehow able
67+ # to create a duplicate variable npm_config_cache. This causes powershell to error "An item with
68+ # the same key has already been added" when attempting to: Get-ChildItem -LiteralPath env:
69+ Write-Host " Squashing duplicate environment variable: $key "
70+ [Environment ]::SetEnvironmentVariable($key , $null )
71+ [Environment ]::SetEnvironmentVariable($key , $originalEnv [$key ])
72+ }
6273}
6374
6475while ($true ) {
@@ -71,20 +82,22 @@ while ($true) {
7182
7283 # Cleanup the environment variables.
7384 $currentMatches = @ { }
74- foreach ($envVar in (Get-ChildItem - LiteralPath env:)) {
85+ foreach ($key in ([Environment ]::GetEnvironmentVariables().Keys)) {
86+ $value = [Environment ]::GetEnvironmentVariable($key )
87+
7588 # Remove the environment variable if it is new.
76- if (! $originalEnv.ContainsKey ($envVar .Name )) {
77- Remove-Item - LiteralPath $envVar .PSPath
78- } elseif ($originalEnv [$envVar .Name ] -ceq $envVar .Value ) {
89+ if (! $originalEnv.ContainsKey ($key )) {
90+ [ Environment ]::SetEnvironmentVariable( $key , $null )
91+ } elseif ($originalEnv [$key ] -ceq $value ) {
7992 # Otherwise record it if it matches.
80- $currentMatches [$envVar .Name ] = $envVar .Value
93+ $currentMatches [$key ] = $true
8194 }
8295 }
8396
84- # Add or update the environment variables that are missing or changed.
85- foreach ($key in $originalEnv.Keys ) {
97+ # Add or update the environment variables that are missing or changed.
98+ foreach ($key in $originalEnv.Keys ) {
8699 if (! $currentMatches.ContainsKey ($key )) {
87- Set-Content - LiteralPath " env: $key " - Value " $ ( $ originalEnv [$key ]) "
100+ [ Environment ]::SetEnvironmentVariable( $key , $ originalEnv [$key ])
88101 }
89102 }
90103
0 commit comments