我想在Powershell中创建一个对象,该对象存储有关脚本状态的信息。我可以这样做:
$myScriptObject =
@("status", "Selected Operation(s):", "None"),
("status", "Current Operation:", "None"),
("status", "Current Step:", "Prompting for Script Action" ),
("test", "This is just for testing", "1,2,3") `
| ForEach-Object {[pscustomobject]@{kind = $_[0]; name = $_[1]; value
= $_[2]}}
那行得通:
$myScriptObject
kind name value
---- ---- -----
status Selected Operation(s): None
status Current Operation: None
status Current Step: Prompting for Script Action
test This is just for testing 1,2,3
...我什至可以做到:
foreach($myObject in $myScriptObject) {
if ($myObject.kind -eq 'status') {
Write-Host $myObject.name $myObject.value
}
}
输出以下内容:
Selected Operation(s): None
Current Operation: None
Current Step: Prompting for Script Action
我的问题是: 1.如何在$ myScriptObject中添加以下内容:
-kind "ActionMenuChoice" -Name "Do This" -Value 1
-kind "ActionMenuChoice" -Name "Do That" -Value 2
如何更改对象中已有的项目?
status Current Step: Prompting for Script Action
到
status Current Step: Prompting for Login
还是我要解决所有问题?这个想法来自于难于从函数返回大量变量的困难,而我阅读使用对象在函数中来回传递要好得多,并且发现使用对象更容易跟踪并在一定程度上进行操纵。
干杯!
答案 0 :(得分:2)
如果我们保留当前的对象数组结构,则可以通过强制转换$myScriptObject
将[collections.generic.list[object]]
创建为通用列表类型。然后,您可以使用.Add()
方法将项目添加到您的集合中。
[collections.generic.list[object]]$myScriptObject =
@("status", "Selected Operation(s):", "None"),
("status", "Current Operation:", "None"),
("status", "Current Step:", "Prompting for Script Action" ),
("test", "This is just for testing", "1,2,3") |
ForEach-Object {[pscustomobject]@{kind = $_[0]; name = $_[1]; value = $_[2]}}
[void]$myScriptObject.add([pscustomobject]@{"Kind" = "ActionMenuChoice"; "Name" = "Do This"; "Value" = 1})
[void]$myScriptObject.add([pscustomobject]@{"Kind" = "ActionMenuChoice"; "Name" = "Do That"; "Value" = 2})
如果要更新该集合中的项目属性,则首先需要在集合中找到对象/项目,然后访问要更新的属性。
($myScriptObject | Where-Object {$_.name -eq 'Current Step:'}).value = "Prompting for Login"
Where-Object
可以提供定位目标对象所需的条件。然后,您可以使用object.property
语法访问该属性。使用PowerShell对象,可以执行直接分配语法(object.property = value
)来更新属性值。
答案 1 :(得分:0)
我会改用数据表:
<ContentPage.ToolbarItems>
<ToolbarItem Icon="icon.png" />
</ContentPage.ToolbarItems>