[英]Returning PSCustomObject Properties From a Function
I'm making a function that prompts for a choice and, upon selecting that choice, it assigned a value to a returned variable's property via a PSCustomObject. 我正在创建一个提示选择的函数,选择该选择后,它会通过PSCustomObject将值分配给返回的变量的属性。
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
}
So if I run the scripted commands independently, it works how I want. 因此,如果我独立运行脚本命令,则可以按我的意愿运行。 I select Choice 1 above and checking the variables shows this: 我选择上面的选择1并检查变量显示如下:
$Results.var1 = "Data 1"
$Results.var2 = "Data 2"
And so on for each other choice. 以此类推。 However, when I wrap it in a function and call it else where, it returns both variables, like so: 但是,当我将其包装在函数中并在其他位置调用它时,它将返回两个变量,如下所示:
$Choices = Select-ChoiceFunction
Select Choice 1 选择选择1
$Results.var1 = "Data 1" "Data 2"
$Results.var2 = "Data 1" "Data 2"
I also tried piping Select-Object
to it like so: 我还尝试将Select-Object
传递给它,如下所示:
$Choices = Select-ChoiceFunction | Select-Object $Results.var1
Select Choice 1 returns with: 选择选择1返回:
"Data 1" "Data 2"
As with above, I'm wanting to call the function and get the variable properties independently. 和上面一样,我想调用该函数并独立获取变量属性。 I assume the function is made incorrectly, but am unclear what I need to add in order to return the properties separately. 我假设该函数的制作不正确,但是不清楚我需要添加什么以便分别返回属性。
UPDATE: Answered by Ansgar/TheMadTechnician. 更新:由Ansgar / TheMadTechnician回答。 I should be calling the properties like this: 我应该这样调用属性:
$Choices = Select-ChoiceFunction
Select Choice 1 选择选择1
$Choices.var1 = "Data 1" "Data 2"
$Choices.var2 = "Data 1" "Data 2"
"You are referencing $Results.var1 and $Results.var2 outside of your function, but you should be looking at $Choices.var1 and $Choices.var2." “您在函数之外引用$ Results.var1和$ Results.var2,但是您应该查看$ Choices.var1和$ Choices.var2。” – TheMadTechnician – TheMadTechnician
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.