我正在创建一个自定义对象,如下所示:
$props = @{
Name = "John"
Gender = "Male"
Age = 30
}
$c = New-Object PSObject -Property $props
对于上面的代码,输出将为:
Name Gender Age ---- ------ --- John Male 30
如何通过更改代码在输出上方添加更多行?
答案 0 :(得分:3)
PS> $people=@()
PS> $people += [PsCustomObject]@{
Name = "John"
Gender = "Male"
Age = 30
}
PS> $people += [PsCustomObject]@{
Name = "Jane"
Gender = "Female"
Age = 20
}
PS> $people
Name Gender Age
---- ------ ---
John Male 30
Jane Female 20
答案 1 :(得分:0)
您可以定义一个数组,然后将多个对象添加到数组中:
#define as array
$people = @()
#build object with the data you want added
$person = New-Object System.Object
$person | Add-Member -NotePropertyName Name -NotePropertyValue "John"
$person | Add-Member -NotePropertyName Gender -NotePropertyValue "Male"
$person | Add-Member -NotePropertyName Age -NotePropertyValue 30
#add object to array
$people += $person
$people
将仅包含John的详细信息:
> $people
Name Gender Age
---- ------ ---
John Male 30
然后您可以以相同的方式添加其他人:
$person = New-Object System.Object
$person | Add-Member -NotePropertyName Name -NotePropertyValue "Jane"
$person | Add-Member -NotePropertyName Gender -NotePropertyValue "Female"
$person | Add-Member -NotePropertyName Age -NotePropertyValue 21
$people += $person
这会将另一个人对象添加到people数组:
> $people
Name Gender Age
---- ------ ---
John Male 30
Jane Female 21
然后您可以检索每个项目:
> $people[1]
Name Gender Age
---- ------ ---
Jane Female 21
或按名称列出特定物品:
> $people[1].Name
Jane
使用foreach循环来获取所有项目的属性和
> foreach ($person in $people) {
Write-Output "$($person.Name) is a $($person.Age) old $($person.Gender)."
}
John is a 30 old Male.
Jane is a 21 old Female.