Thursday, March 17, 2016

Check if WMI class exist on machine through powershell

I was debugging a powershell which throw exception when it tries to GET the WMI class property of the class which does not exist on OS. I found that there are not simple example which explains the code to check the existence of wmi class and then query it property. Therefore i found a code snippet which works perfect for such scenario which check if class exists or not and then you can further query its property.


Example

if(Get-WmiObject -List | where { $_.Name -eq "Win32_PerfRawData_Counters_HyperVDynamicMemoryIntegrationService"})
{
          write-output "class exist"
}
else
{
          write-output "class do not exist"
}


I am checking the existence of wmi class "Win32_PerfRawData_Counters_HyperVDynamicMemoryIntegrationService".

On win2008 r2 / window7 and prev OS it does not exists therefore the code goes in else part.

On latest OS the if block get executed.