Skip to content

Instantly share code, notes, and snippets.

@mkropat
Created September 12, 2017 17:55
Show Gist options
  • Save mkropat/08b84541d895c1a46badff51e3eec80e to your computer and use it in GitHub Desktop.
Save mkropat/08b84541d895c1a46badff51e3eec80e to your computer and use it in GitHub Desktop.
<Query Kind="Program">
<Reference>&lt;RuntimeDirectory&gt;\Microsoft.JScript.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\System.Configuration.Install.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\System.Management.dll</Reference>
<NuGetReference>Newtonsoft.Json</NuGetReference>
<Namespace>Newtonsoft.Json</Namespace>
<Namespace>System.Management</Namespace>
</Query>
void Main()
{
var classes = new[]
{
"Win32_NetworkAdapterConfiguration",
"Win32_OperatingSystem",
"Win32_Processor",
"Win32_Volume",
};
JsonConvert.SerializeObject(Load(classes), Newtonsoft.Json.Formatting.Indented).Dump();
}
static IDictionary<string, object> Load(string[] classes)
{
var result = new Dictionary<string, object>();
foreach (var c in classes)
{
var instances = GetInstances(c);
result[c] = instances.Length == 1 ? (object)instances.Single() : instances;
}
return result;
}
static IDictionary<string,object>[] GetInstances(string className, string scope = null)
{
using (var mgmtClass = new ManagementClass(scope, className, new ObjectGetOptions()))
using (var instances = mgmtClass.GetInstances())
{
return instances.OfType<ManagementObject>()
.Select(x => PropertiesToObject(x.Properties))
.ToArray();
}
}
static dynamic[] Query(string scope, string query)
{
using (var searcher = new ManagementObjectSearcher(scope, query))
{
return searcher.Get()
.OfType<ManagementObject>()
.Select(x => PropertiesToObject(x.Properties))
.ToArray();
}
}
static IDictionary<string,object> PropertiesToObject(PropertyDataCollection properties)
{
var result = new Dictionary<string, object>();
foreach (var p in properties)
result[p.Name] = p.Value;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment