Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ninmonkey/c6bb4dc838e55e4581f86f86e0989f49 to your computer and use it in GitHub Desktop.
Save ninmonkey/c6bb4dc838e55e4581f86f86e0989f49 to your computer and use it in GitHub Desktop.
Colliding Keys Test - Literals don't error and don't lose values

About

I'm experimenting with collisions for the Env var RFC: PowerShell/PowerShell-RFC#384

Cases

Case: fails as expected

$h1 = @{ "path"      = 'foo\bar' }
$h2 = @{ "path`u{0}" = '' }
$h1 + $h2

OperationStopped: Item has already been added. Key in dictionary: 'path'  Key being added: 'path'

Case: same keys, doesn't error when defined inline

$h1 = @{
   "path"      = 'foo\bar'
   "path`u{0}" = ''
}

$h1.keys.count # 2: path, path

$h1 | ConvertTo-Json -Compress
{"path\u0000":"","path":"foo\\bar"}

Case:

$man = @{}
$man[ "path" ]      = 'first'
$man[ "path`u{0}" ] = 'second'
$man[ "path`u{4}" ] = 'third'

$man | ConvertTo-Json -Compress
{"path\u0000":"second","path":"first","path\u0004":"third"}

Hardcoded example

case: Accidentally deletes ENV var depending on order of enumeration

# ensure nothing is defined
[Environment]::SetEnvironmentVariable( "SomePath", '' )
[Environment]::SetEnvironmentVariable( "SomePath`u{0}", '' )
[Environment]::SetEnvironmentVariable( "SomePath`u{4}", '' )

[Environment]::SetEnvironmentVariable( "SomePath", '/foo/start' )
[Environment]::SetEnvironmentVariable( "SomePath`u{0}", '' )
gci "env:\SomePath*"

# No keys found. SomePath was deleted. 

Ex: No collision, but maybe this should error? They probably didn't mean to create 2 new env vars?

# ensure nothing is defined
[Environment]::SetEnvironmentVariable( "SomePath", '' )
[Environment]::SetEnvironmentVariable( "SomePath`u{0}", '' )
[Environment]::SetEnvironmentVariable( "SomePath`u{4}", '' )

[Environment]::SetEnvironmentVariable( "SomePath", '/foo/start' )
[Environment]::SetEnvironmentVariable( "SomePath`u{4}", '/bar/other' )
gci "env:\SomePath*"  |Ft -AutoSize

# Set 2 variables:

Name      Value
----      -----
SomePath /bar/other
SomePath  /foo/start

Environment

Pwsh: 7.4.6
OS: windows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment