为什么$ hash.key语法在ExpandString方法中不起作用?

Myr*_*rys 8 syntax powershell powershell-3.0

以下Powershell脚本演示了此问题:

$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
Run Code Online (Sandbox Code Playgroud)

任何人都知道为什么$hash.key语法在任何地方都可以工作 这可以修复,还是我必须把它搞砸并使用$hash[''key'']语法?

Jas*_*irk 1

ExpandString api 并不完全适合在 PowerShell 脚本中使用,它是为 C# 代码添加的。您的示例不起作用仍然是一个错误(我认为它已在 V4 中修复),但这确实意味着有一种解决方法 - 我建议一般使用。

双引号字符串有效地(但不是字面上)调用 ExpandString。所以下面的应该是等价的:

$ExecutionContext.InvokeCommand.ExpandString('$($hash.a)')
"$($hash.a)"
Run Code Online (Sandbox Code Playgroud)