LaPhi
LaPhi

Reputation: 5907

WMI - query multiple details

I want to get multiple details from a few servers in my environment.

This code is working, but is this code a good way to get the details ?

Is it ok to call "new ManagementObjectSearcher" at every request ?

ManagementObjectSearcher cpuUsage = new ManagementObjectSearcher
          ("\\\\" + strComputer + "\\root\\CIMV2", 
          "SELECT * FROM Win32_Processor");

foreach (ManagementObject queryObj in cpuUsage.Get())
{
    Console.WriteLine("LoadPercentage: {0}", queryObj["LoadPercentage"]);
}
    
ManagementObjectSearcher totalRAM = new ManagementObjectSearcher
           ("\\\\" + strComputer + "\\root\\CIMV2", 
           "SELECT * FROM Win32_ComputerSystem");

foreach (ManagementObject queryObj in totalRAM.Get())
{
  Console.WriteLine("TotalPhysicalMemory: {0}", queryObj["TotalPhysicalMemory"]);
}
    
ManagementObjectSearcher freeRAM = new ManagementObjectSearcher
      ("\\\\" + strComputer + "\\root\\CIMV2", 
          "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");

foreach (ManagementObject queryObj in freeRAM.Get())
{
    Console.WriteLine("AvailableMBytes: {0}", queryObj["AvailableMBytes"]);
}

Upvotes: 1

Views: 1540

Answers (2)

wilx
wilx

Reputation: 18238

I have done something similar. My application is longer running so I keep one ManagementScope per machine and one ManagementObjectSearcher per query per machine. I only dispose of these objects when if I get any error during a query.

Upvotes: 1

stuartd
stuartd

Reputation: 73283

You should reuse the ManagementObjectSearcher as it connects to the server each time and that will be an overhead.

For a little more efficiency, instead of using SELECT * FROM in your wql you can specify what properties you want, ie

SELECT LoadPercentage FROM Win32_ComputerSystem

Upvotes: 1

Related Questions