在Powershell中通过引用传递hashtable之后进行Splatting

时间:2012-11-11 10:56:45

标签: powershell hashtable pass-by-reference

当我通过引用一个用于splatting的函数传递哈希表时,我遇到了麻烦。我该如何解决这个问题?

Function AllMyChildren {
    param (
        [ref]$ReferenceToHash
    }
    get-childitem @ReferenceToHash.Value
    #  etc.etc.
}
$MyHash = @{
    'path' = '*'
    'include' = '*.ps1'
    'name' = $null
}
AllMyChildren ([ref]$MyHash)
  

结果:错误(“Splatted变量不能用作属性或数组表达式的一部分。将表达式的结果分配给临时变量,然后改为映射临时变量。”)。

试图这样做:

$newVariable = $ReferenceToHash.Value
get-childitem @NewVariable

根据错误消息确实有效。在这种情况下,它是首选语法吗?

1 个答案:

答案 0 :(得分:4)

1)使用[ref]传递哈希表(或类的任何实例,即引用类型)是没有意义的,因为它们总是通过引用自身传递。 [ref]与值类型(标量和结构实例)一起使用。

2)splatting运算符可以直接应用于变量,而不是表达式。

因此,为了解决问题,只需按原样传递函数中的哈希表:

Function AllMyChildren {
    param (
        [hashtable]$ReferenceToHash # it is a reference itself
    )
    get-childitem @ReferenceToHash
    #  etc.etc.
}
$MyHash = @{
    'path' = '*'
    'include' = '*.ps1'
    'name' = $null
}
AllMyChildren $MyHash
相关问题