|
Testing object arrays using Compare-Object and -contains I'm having trouble finding a simple scheme for getting all objects which are
members of a set B but not also members of another set A.
The specific real problem is a tool for loading all registered snapins
automatically, but only attempting to do so if they are not already loaded.
I could of course do this:
Get-PsSnapin -Registered | Add-PSSnapin -ea SilentlyContinue
for quiet output, but that would be cheating (and would kill errors due to
reasons other than the snapin being already loaded).
We can get all loaded snapins like this:
$Loaded = Get-PSSnapin
and we can get all registered snapins like this:
$Registered = Get-PSSnapin -Registered
but $Loaded will contain any registered snapins that are already loaded.
I initially tried to test for containment, but the -contains operator does
not appear to work correctly for objects; it apparently compares members by
identity, and the PSSnapInInfo objects never test as identical; e.g., even
if all of the registered snapins are already loaded,
Get-PSSnapin -Registered | ?{$Loaded -notcontains $_}
passes through all of the objects.
Trying to do a Select-Object Name on each set doesn't correctly filter
identical items either.
Since -notcontains works fine on a simple array, my current approach is
this:
$Loaded = Get-PSSnapin | ForEach-Object {$_.Name}
Get-PSSnapin -Registered | ForEach-Object {
Where-Object {$Loaded -notcontains $_.Name}
} | Add-PSSnapin
I also checked into using Compare-Object. I like the way it works in terms
of the thinking behind it, but it takes some low-level unboxing to work
right. The shorthand is pretty lengthy:
diff (gsnp) (gsnp -r) | ?{$_.SideIndicator -eq "=>"} | %{
$_.InputObject} | asnp
and a fully-described comparison is very long:
Compare-Object (Get-PSSnapin) (Get-PSSnapin -Registered) |
Where-Object {$_.SideIndicator -eq "=>"} |
ForEach-Object {$_.InputObject} |
Add-PSSnapin
Compare-Object also takes a while to run; this is not really the kind of
thing it was specifically designed to do.
Does anyone have any better ideas on how to approach this? |