Created
September 12, 2017 17:55
-
-
Save mkropat/08b84541d895c1a46badff51e3eec80e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Query Kind="Program"> | |
<Reference><RuntimeDirectory>\Microsoft.JScript.dll</Reference> | |
<Reference><RuntimeDirectory>\System.Configuration.Install.dll</Reference> | |
<Reference><RuntimeDirectory>\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