How to use Microsoft.Management.Infrastructure (MMI) instead of System.Management for local WMI queries

3.2k Views Asked by At

I have this snippet for getting Windows Version using WMIC

(from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
                    select x.GetPropertyValue("Version")).FirstOrDefault().ToString();

As the WMI is considered now legacy and .NET Core implementation of System.Configuration requires up-to-date .NET Framework, it seems this information needs to be retrieved using MMI.

Surprisingly, every Windows problem that requires WMI access has something like the snippet above. Looks like MMI adoption isn't that high yet and it's not easy to find a good MMI examples.

How can I use Microsoft.Management.Infrastructure to accomplish the code above?

1

There are 1 best solutions below

1
On BEST ANSWER
CimSession.Create(null) // null instead of localhost which would otherwise require certain MMI services running
                .QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem")
                .FirstOrDefault().CimInstanceProperties["Version"].Value.ToString();

A small note for .NET Core: Due to some runtime identifier issues with Microsoft.Management.Infrastructure package, I had to add this to csproj file (x86 intended for our use-case):

<RuntimeIdentifier>win7-x86</RuntimeIdentifier>