下面的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