使用对象的属性绘制函数

时间:2017-10-25 08:42:41

标签: powershell powershell-v5.0 splat

在PowerShell中,您可以将多个参数传递给函数或cmdlet,方法是将它们包装在哈希表变量中,然后传递前缀为@而不是$的变量。

是否可以使用哈希表进行splat,哈希表是另一个对象的属性(即作为一个内容)?例如下面我首先要将属性(testInttestString)分配给另一个变量,然后再将其展开到Demo。我想要一些方法来避免这个额外的步骤,但一直无法找到一个简洁的解决方案......

function Demo {
    [CmdletBinding()]
    Param (
        [Parameter()]
        [string]$One
        ,
        [Parameter()]
        [string]$Two
    )
    "1 = $One"
    "2 = $Two"
}
$test = @{
    testInt = @{ 
        One = '1'
        Two = '2'
    }
    testString = @{
        One = 'One'
        Two = 'Two'
    }
}

$t = $test.testInt
Demo @t 
$t = $test.testString
Demo @t

Demo @test.testInt #this doesn't work / I've also tried similar options with various castings and braces though to no avail.

更新

建议提交:https://github.com/PowerShell/PowerShell/issues/5227

1 个答案:

答案 0 :(得分:4)

AFAIK展开对象属性或数组或散列表元素的唯一方法是将其分配给变量然后splat该变量

INSERT INTO tblEntrants(AccountID,compID) SELECT(CASE WHEN (SELECT resultplayer1 FROM tblfixtures) > (SELECT resultplayer2 FROM tblfixtures) THEN (SELECT player1 FROM tblfixtures) END), @compID

INSERT INTO tblEntrants(AccountID,compID) SELECT(CASE WHEN (SELECT resultplayer2 FROM tblfixtures) > (SELECT resultplayer2 FROM tblfixtures) THEN (SELECT player2 FROM tblfixtures) END), @compID

符号$p = $variable.property demo @p 无效,@variable.property@()都不能用于允许这样的语法,因为它们已经有不同的含义(数组构造和哈希表构造)。