从函数返回PSCustomObject属性

时间:2018-01-09 22:33:46

标签: powershell scripting powershell-v4.0

我正在创建一个提示选择的函数,并在选择该选项后,通过PSCustomObject为返回的变量属性赋值。

config.Entity<Product>()
    .HasIndex(b => b.ProductId)
    .IsUnique()
    .HasFilter(null);

因此,如果我独立运行脚本命令,它会按我想要的方式运行。我选择上面的选择1并检查变量显示:

function Select-ChoiceFunction {
    # This generates a simple choice menu #
    $Title = "Title"
    $Info = "Info"
    $choice = echo @("Choice &1", "Choice &2", "Choice &3", "&Cancel")
    [int]$defaultchoice = 3
    $selection = $host.UI.PromptForChoice($title, $info, $choice, $defaultchoice)

    # Switch assigns two pieces of data to two variables #
    switch ($selection) {
        0 {
            $var1 = "Data 1"
            $var2 = "Data 2"
            Write-Host "`Choice 1`n"; break
        }
        1 {
            $var1 = "Data 3"
            $var2 = "Data 4"
            Write-Host "`Choice 2`n"; break
        }
        2 {
            $var1 = "Data 5"
            $var2 = "Data 6"
            Write-Host "`Choice 3`n"; break
        }
        default {
            $WarningPreference = "Stop"
            Write-Warning "`nNo Choice Made.`n"
        }
    }

    # Creating PSObject to return Properties from selection outside the Function #
    $Results = [PSCustomObject]@{
        var1 = $var1
        var2 = $var2
    }

    return $Results
}

等等其他选择。但是,当我将它包装在一个函数中并在其他地方调用它时,它会返回两个变量,如下所示:

$Results.var1 = "Data 1"
$Results.var2 = "Data 2"

选择选择1

$Choices = Select-ChoiceFunction

我也试过像这样管道$Results.var1 = "Data 1" "Data 2" $Results.var2 = "Data 1" "Data 2"

Select-Object

选择选项1返回:

"Data 1" "Data 2"

如上所述,我想要调用该函数并独立获取变量属性。我认为该功能不正确,但我不清楚我需要添加什么才能单独返回属性。

更新:Ansgar / TheMadTechnician回答。我应该打电话给这样的房产:

$Choices = Select-ChoiceFunction | Select-Object $Results.var1

选择选择1

$Choices = Select-ChoiceFunction

1 个答案:

答案 0 :(得分:0)

&#34;您在函数之外引用$ Results.var1和$ Results.var2,但您应该查看$ Choices.var1和$ Choices.var2。&#34; - TheMadTechnician