Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't $hash.key syntax work inside the ExpandString method?

The following Powershell script demonstrates the issue:

$hash = @{'a' = 1; 'b' = 2}
Write-Host $hash['a']        # => 1
Write-Host $hash.a           # => 1

# Two ways of printing using quoted strings.
Write-Host "$($hash['a'])"   # => 1
Write-Host "$($hash.a)"      # => 1

# And the same two ways Expanding a single-quoted string.
$ExecutionContext.InvokeCommand.ExpandString('$($hash[''a''])') # => 1
$ExecutionContext.InvokeCommand.ExpandString('$($hash.a)')      # => Oh no!

Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an object."
At line:1 char:1
+ $ExecutionContext.InvokeCommand.ExpandString('$($hash.a)')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NullReferenceException

Anyone know why the $hash.key syntax works everywhere but inside explicit expansion? Can this be fixed, or do I have to suck it up and live with the $hash[''key''] syntax?

like image 875
Myrddin Emrys Avatar asked Jul 23 '12 02:07

Myrddin Emrys


1 Answers

I use this method, since this bug exists in v4 (not in v5)

function render() {
    [CmdletBinding()]
    param ( [parameter(ValueFromPipeline = $true)] [string] $str)

    #buggy
    #$ExecutionContext.InvokeCommand.ExpandString($str)

    "@`"`n$str`n`"@" | iex
}

Usage for your example:

  '$($hash.a)' | render
like image 65
majkinetor Avatar answered Oct 13 '22 00:10

majkinetor