Splatting a function with an object's property

牧云@^-^@ 提交于 2019-12-11 07:59:09

问题


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:


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).



来源:https://stackoverflow.com/questions/46927822/splatting-a-function-with-an-objects-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!