Using Powershell cmdLet “Compare-Object” to compare WMI objects
Recently I came across a scenario where one of the developers wanted to automate to produce a list of Products that are not installed on a box, compared to a reference server. He was looking for a powershell solution for the same.
If you are familiar with WMI, you may obviously want to explore the possibility of using the WMI class Win32_Product and I was no different.
Below are steps one may follow to achieve the above goal
1. Export the list of Installed Product on the Reference Server and Server to be compared using Win32_Product class and the Export-CliXML cmdLet
2. Import them back to a Powershell objects using Import-CliXML cmdLet
3. Compare the Powershell Objects collection using Compare-Object cmdLet using the property to be matched.
A sample Powershell command block may look like below
# Export function to be executed on the reference server
(get-wmiobject -class 'Win32_Product' ) | Export-Clixml c:\Reference.xml
#Export function to be executed on other servers to be examined
(get-wmiobject -class 'Win32_Product' ) | Export-Clixml c:\Server1.xml
#Imports xml objects as powershell objects (This assume that we already have objects exported to XML file and kept on C:\)
$RefObject = Import-Clixml C:\Reference.xml
$Server1Objects = Import-Clixml c:\Server1.xml
#Execute Compare-Object to find out the differences
$diffObjects = Compare-Object $RefObject $Server1Objects -Property name
#$diffObjects now contains the difference between the installed products on two servers
$diffObjects
A Sample output of above command block may look like below
The above output shows the difference in the installed products between two servers. A ‘SideIndicator’ value ‘ <=’ indicates The object present only on the Reference Server and the value ‘ =>’ indicates the object is present only on the comparing machine
This article shows how to compare the objects of Win32_Product class. In fact it can be used for any objects like Win32_Process, Win32_Processor etc…
PS: The above method works only if we export the objects without Format-Table cmdlet.