0

想要填充以下 PSObject,以便它可以在 IP 和主机名之间具有一对一或一对多的关系。

$hostobj = New-Object PSOBject
$hostobj | Add-Member -MemberType NoteProperty -Name "ip_address" -Value ""
$hostobj | Add-Member -MemberType NoteProperty -Name "hostnames" -Value ""

这给了我正确的标题,但是当我尝试添加多个值时,尝试添加重复值时会出错:

$hostobj = New-Object PSOBject
$hostobj | Add-Member -MemberType NoteProperty -Name "ip_address" -Value "1.1.1.1"
$hostobj | Add-Member -MemberType NoteProperty -Name "hostnames" -Value "server1"
$hostobj | Add-Member -MemberType NoteProperty -Name "ip_address" -Value "2.2.2.2"
$hostobj | Add-Member -MemberType NoteProperty -Name "hostnames" -Value "server2"

为什么是这样?

可以相当容易地做到一对多:

$hostobj = New-Object PSOBject
$hostobj | Add-Member -MemberType NoteProperty -Name "ip_address" -Value "1.1.1.1"
$hostobj | Add-Member -MemberType NoteProperty -Name "hostnames" -Value "server1", "server2", "server3"

其中任何一个都是额外的数据集:

1.1.1.1     server1     
2.2.2.2     server2
3.3.3.3     server3
4.5.6.7     server4     server5     server6     server7     
8.8.8.8     server8     
9.9.9.9     server9

1.1.1.1
server1
2.2.2.2
server2
3.3.3.3
server3
4.5.6.7
server4
server5
server6
server7
8.8.8.8
server8
9.9.9.9
server9
4

1 回答 1

0

您想创建一个对象列表,例如:

$ArrayList = New-Object System.Collections.ArrayList

$hostobj = New-Object PSOBject
$hostobj | Add-Member -MemberType NoteProperty -Name "ip_address" -Value "1.1.1.1"
$hostobj | Add-Member -MemberType NoteProperty -Name "hostnames" -Value "server1"

$ArrayList.Add($hostobj)

$hostobj = New-Object PSOBject
$hostobj | Add-Member -MemberType NoteProperty -Name "ip_address" -Value "2.2.2.2"
$hostobj | Add-Member -MemberType NoteProperty -Name "hostnames" -Value "server2"

$ArrayList.Add($hostobj)

这样就$ArrayList包含了所有的宿主对象。并且每个对象都有一个ip_address和的值hostnames

如果这对您没有帮助,请指定您的期望/您正在尝试做什么/使用什么。

于 2018-08-08T15:02:28.013 回答