下面的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
任何人都知道为什么$hash.key
语法作品无处不在,但明确的扩张里面?这可以修复吗?还是我必须吸取它并与$hash[''key'']
语法一起生活?
它实际上比这更糟糕 - 我不能得到*任何*实际的子表达式扩展使用这种语法,只有简单的东西,如$($ foo)工作,例如'$(Get-Date | select -expand DayOfWeek)'会引发同样的异常。建议在连接上报告它,这是突破变化/错误的IMO。 – BartekB 2012-07-23 11:38:00
报告它在哪里?在这种情况下,我不知道“连接”是什么意思。 – 2012-07-23 15:49:01
对不起,应该更具体......:http://connect.microsoft.com/powershell->报告这类问题的最佳地点。 – BartekB 2012-07-23 21:58:19