我试图比较名为" name"的两个对象属性。并且包含相同类型的数据,在本例中为服务器主机名。对象不相同AKA没有相同的属性。简而言之,我试图比较两个服务器名称列表并确定它们丢失的位置(哪个对象)。
我希望找到每个对象中缺少的项目(服务器主机名)。当发现某些东西时,我希望获得它所在的给定对象中的项目的所有相关属性。我可以成功地执行compare-object,但不知道如何获得结果I && #39;我正在寻找。
我认为可以为每个创建两个新对象,列出在另一个对象中找不到的项目可能吗?或者我以不同的方式使用compare-object的输出引用先前的对象并生成一些格式化的输出?
此代码目前生成一个空白文件。
数据格式:
$ SNObject:
名,IP,类
server-place.com,10.10.10.10,windows server
$ QRObject:
姓名,日期,IP,一般,设备类型
server-place1.com,11.11.11.11,随机信息,linux服务器
代码示例:
$compare = compare-object $SNObject $QRObject -property Name |
foreach {
if ($_.sideindicator -eq '<=')
{$_.sideindicator = $PathToQRReport }
if ($_.sideindicator -eq '=>')
{$_.sideindicator = $PathToSNReport}
}
$compare |
select @{l='Value';e={$_.InputObject}},@{l='File';e={$_.SideIndicator}} |
Out-File -FilePath C:\Temp\MissingOutputs1.txt
答案 0 :(得分:1)
啊......只是想到了一个替代方案,可能会给你提供你正在寻找的东西,但方式略有不同:
## Join both arrays into single array and then group it on the property name that has a shared value, 'name'
$all = @()
$group = @($SNObject + $QRObject)
$group | Group-Object -Property name | % {
## Create a custom object that contains all possible properties plus a directionality indicator ('source')
$n = New-Object PSObject -Property @{
'name' = ''
'date' = ''
'ip' = ''
'general' = ''
'platform' = ''
'source' = ''
}
if ($_.Count -eq 1) {
## Loop through the grouped results and determine their source and write properties based off of their source
foreach ($i in $_.Group) {
if (@($i | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty name) -contains 'date' ) {
## This value came from $QRObject which apparently is the only dataset that contains a date property
$n.source = 'QRObject'
$n.date = $i.date
$n.general = $i.general
$n.platform = $i.'device type'
} else {
## This object does not contain the 'date' property, therefore it came from $SNObject
$n.source = 'SNObject'
$n.platform = $i.class
}
## write out common properties
$n.name = $i.name
$n.ip = $i.ip
## add the custom PSObject back to a master array with all formatted properties
$all += $n
}
}
}
$all | out-whereever-you-want