根据一个属性在两个不同的Powershell对象中查找匹配项

时间:2013-11-05 18:56:16

标签: powershell

我试图在两种不同类型的Powershell对象中找到匹配的名称

$ Object1有两个属性 - Name(字符串),ResourceID(uint32)

$ object2有一个noteproperty - Name(system.string)

这给了我一个匹配名称的列表,但我也想要$ object1中相应的resourceID属性。

$computers = Compare-Object $Object1.name $WSD_CM12 | where {$_.sideindicator -eq "=>"} | foreach {$_.inputobject}

这些是超过10,000件物品的大型物品,所以我正在寻找最有效的方法来实现这一目标。

2 个答案:

答案 0 :(得分:1)

如果我理解你所追求的是什么,我首先要从你的Object1集合中创建一个哈希表:

$object1_hash = @{}
 Foreach ($object1 in $object1_coll)
  { $object1_hash[$object1.Name] = $object1.ResourceID }

然后您可以找到任何给定Object2.name的ResourceID:

$object1_hash[$Object2.Name]

用于创建哈希表的测试平台:

$object1_coll = $(
 New-Object PSObject -Property @{Name = 'Name1';ResourceID = 001}
 New-Object PSObject -Property @{Name = 'Name2';ResourceID = 002}
 )

$object1_hash = @{}
 Foreach ($object1 in $object1_coll)
  { $object1_hash[$object1.Name] = $object1.ResourceID }

$object1_hash

Name                       Value                                                                                             
----                       -----                                                                                             
Name2                          2                                                                                                 
Name1                          1                                                                                                 

答案 1 :(得分:0)

替代方法:

# Create sample list of objects with both Name and Serial
$obj1 = New-Object -Type PSCustomObject -Property:@{ Name = "Foo"; Serial = "1234" }
$obj2 = New-Object -Type PSCustomObject -Property:@{ Name = "Cow"; Serial = "4242" }
$collection1 = @($obj1, $obj2)

# Create subset of items with only Name
$objA = New-Object -Type PSCustomObject -Property:@{ Name = "Foo"; }
$collection2 = @($objA)

#Everything above this line is just to make sample data
# replace $collection1 and $collection2 with $Object1, $WSD_CM12
# Combine into one list
($collection1 + $collection2) | 
    # Group by name property
    Group-Object -Property Name | 
    # I only want items that exist in both
    Where { $_.Count -gt 1 } | 
    # Now give me the object
    Select -Expand Group |
    # And get the properties
    Where { $_.Serial -ne $null }