如何使用 Microsoft.Management.Infrastructure (MMI) 而不是 System.Management 进行本地 WMI 查询

Nat*_*tan 4 c# windows system.configuration .net-core

我有这个使用 WMIC 获取 Windows 版本的代码段

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

由于 WMI 现在被认为是遗留系统,并且System.Configuration 的 .NET Core 实现需要最新的 .NET Framework,因此似乎需要使用 MMI 检索此信息。

令人惊讶的是,每个需要 WMI 访问权限的 Windows 问题都有类似上面的代码片段。看起来 MMI 的采用率还没有那么高,而且要找到一个好的 MMI 示例并不容易。

我如何使用Microsoft.Management.Infrastructure来完成上面的代码?

Nat*_*tan 5

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();
Run Code Online (Sandbox Code Playgroud)

.NET Core 的一个小说明:由于Microsoft.Management.Infrastructure package 的一些运行时标识符问题,我不得不将其添加到 csproj 文件(x86 用于我们的用例):

<RuntimeIdentifier>win7-x86</RuntimeIdentifier>
Run Code Online (Sandbox Code Playgroud)