为什么 $hash.key 语法在 ExpandString 方法中不起作用? [英] Why doesn't $hash.key syntax work inside the ExpandString method?
本文介绍了为什么 $hash.key 语法在 ExpandString 方法中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下 Powershell 脚本演示了该问题:
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
有谁知道为什么 $hash.key
语法除了在显式扩展之外在任何地方都有效?这可以解决吗,还是我必须接受它并使用 $hash[''key'']
语法?
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?
推荐答案
我用这个方法,因为这个bug存在于v4中(v5中没有)
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
}
示例用法:
'$($hash.a)' | render
这篇关于为什么 $hash.key 语法在 ExpandString 方法中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文