The other day in the #powershell IRC channel on freenode, a regular wanted to know how to find out the difference in properties between two objects. He had an object with 100 properties and another with about 120 or so and wanted to know which ones were unique in the second object. Compare was the natural first place to look, but it really is good for telling the difference in CONTENT rather than SCHEMA (the object properties). Here is an example of an easy way to do this.
$a = 1 | select-object name, age , sex
$b = 1 | select-object species, name , age
$a.psobject.properties | % { $_.name } | ? {$($b.psobject.properties | % { $_.name } ) -notcontains $_ }$b.psobject.properties | % { $_.name } | ? {$($a.psobject.properties | % { $_.name } ) -notcontains $_ }
Here we simply create a couple of objects that have some similar and different properties. then the first example shows the properties in A that aren't in B, and the next shows the properties in B that aren't in A.
The main trick here is .psobject ... all objects have a "hidden" psobject property that contains some cool PowerShell related stuff, including the properties. There are some good blog entries around on psobject and its definitely worth a deeper look. This technique is also the basis on a script i will introduce soon, my join-object function.
-Karl
Technorati Tags:
powershell