Splatting a function with an object's property

2019-07-31 01:26发布

In PowerShell you can pass multiple parameters to a function or cmdlet by wrapping them in a hashtable variable, then passing that variable prefixed with @ instead of $.

Is it possible to splat with a hashtable which is a property of another object (i.e. as a one liner)? e.g. below I first have to assign the property (testInt, testString) to another variable before I can splat it to Demo. I'd like some way to avoid this additional step, but haven't been able to find a neat solution...

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.

Update

Suggestion submitted: https://github.com/PowerShell/PowerShell/issues/5227

1条回答
相关推荐>>
2楼-- · 2019-07-31 01:43

AFAIK the only way to splat an object property or an element of an array or hashtable is to assign it to a variable and then splat that variable

$p = $variable.property
demo @p

The notation @variable.property is invalid, and neither @() nor @{} could be used to allow such syntax, since they already have different meanings (array construction and hashtable construction).

查看更多
登录 后发表回答