0

I am trying to find the matching names in two different types of Powershell objects

$Object1 has two properties - Name (string), ResourceID (uint32)

$object2 has one noteproperty - Name (system.string)

This gives me a list of the matching names but I also want the corresponding resourceID property from $object1.

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

These are big objects with over 10,000 items so I'm looking for the most efficient way to accomplish this.

4

2 回答 2

1

If I'm understanding what you're after, I'd start by creating a hash table from your Object1 collection:

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

Then you can find the ResourceID for any given Object2.name with:

$object1_hash[$Object2.Name]

Test bed for creating hash table:

$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                                                                                                 
于 2013-11-05T19:06:44.390 回答
0

Alternative method:

# 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 }
于 2013-11-05T20:52:13.003 回答