如何将对象的点状属性作为变量传递?

时间:2019-11-13 00:10:29

标签: powershell powershell-5.0

我是StackOverflow的新手,但不是PowerShell的所有新手...我正在编写一个使用$host.UI.PromptForChoice()方法向用户显示选项列表的函数。它需要一个对象数组,读取一个属性以用作标签,然后在屏幕上显示选择。当用作标签的属性是一个简单的字符串时,该函数可以正常工作。当标签所需的属性深达两个(或更多)级别时,它将不起作用。

例如:

$object[i].base变成$object[i].$var($ var =“ base”)<-可行!

$object[i].base.name变为$object[i].$var($ var =“ base.name”)<-这将不返回任何内容。

我尝试了使用变量的各种方式,而没有任何改变。 $object.{$var} $object.($var) $object."$var"

我几乎可以肯定这是关于“。”的问题在变量中被解释。都是一个字符串。

这是全部功能。我从互联网上的另一篇文章中借用了此代码的基础知识,但是现在我再也找不到了。我向作者表示歉意,因为他们没有正确地相信他们!

function Show-UserChoices {
        param (
        [Parameter(Mandatory=$true)]
        $InputObject,
        [Parameter(Mandatory=$true)]
        [string]$LabelProperty,
        [string]$Caption = "Please make a selection",
        [string]$Message = "Type or copy/paste the text of your choice",
        [int]$DefaultChoice = -1
    )
    $choices = @()
    for($i=0;$i -lt $InputObject.Count;$i++){
        $choices += [System.Management.Automation.Host.ChoiceDescription]("$($InputObject[$i].$LabelProperty)")
    }
    $userChoice = $host.UI.PromptForChoice($Caption,$Message,$choices,$DefaultChoice)
    return $userChoice
}

任何有关我在这里缺少的建议都将受到赞赏!

更新:

我找到了处理属性的解决方案。如果我将每个属性标签作为数组中的索引传递,则可以在函数中汇编表达式并运行它。它可能不是最漂亮的代码,但是可以满足我的需要。这是我更改的内容:

 .example
    Show-UserChoices -InputObject $object -LabelProperty foo,bar
    This will construct the expression $object.foo.bar

 [string[]]$LabelProperty, <-- now accepts an array of strings


$choices = @()
    for($i=0;$i -lt $InputObject.Count;$i++){
        $exp = '$InputObject[$i]'
        foreach ($j in $LabelProperty){
            $exp += '.' + $j
        }
        $choices += [System.Management.Automation.Host.ChoiceDescription]("$(Invoke-Expression $exp)")
    }

0 个答案:

没有答案