Tuesday, September 2, 2008

Collecting machine information using WMI

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/collecting_machine_information_using_wmi.htm]

Like most developers, I want a fast machine. And like most developers, despite my best efforts, I inevitably find myself coding on a machine that isn't quite fast "enough". One of the things I'm trying to track this down is making my own simple performance benchmark tool (if you know of a tool that works great for you, please feel free to suggest it). And as long as such a tool is running benchmarks, I'd like to collect relevant machine information like memory, disk space, etc...


Thanks to Windows Management Instrumentation (WMI), this actually ended up being easier than I thought. There's a lot of different ways to call from the API, here's one example (I saw this template from somewhere else online, cannot remember where):


      //Add namespace, in assembly "System.Management"

      //using System.Management;


      //Put this code in your method:

      ManagementObjectSearcher mos =
        new ManagementObjectSearcher("WMI_query");
      foreach (ManagementObject mob in mos.Get())
        foreach (PropertyData pyd in mob.Properties)
          if (pyd.Name == "WMI_Property_Name")
            return pyd.Value;  //May need to convert type


where "WMI_query" is your select query, and "WMI_Property_Name" is the name of the property you want to return. The gist is that you can write WMI queries (a simple string), much like SQL queries, to get machine information. Some sample queries could be:

  • "SELECT Free_Physical_Memory FROM Win32_OperatingSystem"

  • "SELECT Total_Physical_Memory FROM Win32_ComputerSystem"

  • "SELECT Free_Space,Size,Name from Win32_LogicalDisk where DriveType=3"

  • "SELECT Name FROM Win32_Processor" //I've seen this occasionally give problems, someone suggested I try the advice from here instead.

Here's a quick tutorial.

Here's the official MSDN reference for WMI queries. There are hundred of things to query on, so a lot of it is knowing which query to write.


Note that these queries can be run from other scripting languages, like VBScript, so it's not just a C# thing. I'd expect this to be very popular with most IT departments.


It's also useful if you wanted to make a quick tool on your build servers to detect the free disk space, and have a scheduled task kick it off every night, and then log your results to a database. If you have a distributed build system (i.e. several servers are required for all your different builds), then it's a nice-to-have.

No comments:

Post a Comment