Reputation: 153
The specific problem I am trying to solve is with a list of VMs and their hosts that I derived using powercli, but I think this is a question that might be asked more generally for any list of powershell objects.
I have a list of objects and their properties. I would like to compare each object in that list to all other objects in that list, and see which of those VMs have that property in common.
$vms = Get-VM | Where-Object {$_.Name -like '*vma*'} | Select Name, VMHost
Is there a relatively simple way to then iterate through the list and compare each objects to every other object in that list and see which objects have an identical "VMHost" property? Most of the questions I have found are about comparing two arrays of objects, but I'm not sure that helps here.
The end goal is to generate a report which highlights VMs whose names match a specific string and share a host, so that they can be checked manually and moved to other hosts if needed.
Upvotes: 1
Views: 506
Reputation: 153
Keeping in mind the end goal, I ended up with the following:
$vms = Get-VM | Where-Object {$_.Name -like '*vma*'} | Select Name, VMHost
$groupedvms = $vms | Group-Object -Property VMHost
I then used the $x.count variable to determine if the VMs shared a host. I did this by checking if the groups that were created by the Group-Object command had more than one object assigned to them (if the count was > 1) and then generating output based on that.
foreach ($vmgroup in $groupedvms) {
if ($vmgroup.count -ne 1) { [...] }
else { [...] }
}
This let me generate the report I needed. There's probably a better way to do this but this worked quite well for what I needed (a quick-and-dirty email report to be run on a daily basis and triaged if needed).
Upvotes: 2
Reputation: 1620
From here:
$b = $a | select –unique
Compare-object –referenceobject $b –differenceobject $a
Selects the unique objects, then compares that to the full list so you can check for what was not copied over.
Upvotes: 2