It can be done in your code via WMI. I've found a tool from Microsoft that creates code for it.
The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.
You can download it here.