在没有 WS-Management 服务的情况下通过 MI 访问 WMI 实例

Access WMI instances via MI without WS-Management service

我正在尝试通过 Microsoft.Management.Infrastructure API 从 C# 访问嵌入在 Windows 7 和 Windows 10 上的 WMI 类。 它使用以下代码段中的代码工作,但前提是我启动 Windows 远程管理 (WS-Management) 服务。

我注意到即使 WS-Management 服务未启动,我也可以通过 Powershell cmdlet(如 Get-WmiObject)访问 类。如果没有通过 Microsoft 管理基础结构 APIs 启动服务,是否有任何方法可以访问 WMI?

CimSession cimSession = CimSession.Create("localhost");
IEnumerable<CimInstance> enumeratedInstances = cimSession.EnumerateInstances(@"root\cimv2", "Win32_Process");
foreach (CimInstance cimInstance in enumeratedInstances)
{
    Console.WriteLine("{0}", cimInstance.CimInstanceProperties[ "Name" ].Value.ToString());
}

如果您在本地工作,那么您应该始终能够访问 WMI。来自 MSDN 文档:

WMI runs as a service with the display name "Windows Management Instrumentation" and the service name "winmgmt". WMI runs automatically at system startup under the LocalSystem account. If WMI is not running, it automatically starts when the first management application or script requests connection to a WMI namespace.

您还可以使用 ORMi(非常易于使用)WMI 库在 WMI 类 和 C# 模型之间自动映射。

[WMIClass("Win32_Process")]
public class Process
{
    public string Name { get; set; }
    public string Description { get; set; }
}

然后查询:

WMIHelper helper = new WMIHelper("root\CimV2");

List<Process> process = helper.Query<Process>().ToList();

所以,我遇到了同样的问题。此外,Windows.Management.Instrumentation 在 .NET Core 中不可用,但 Microsoft.Management.Infrastructure 可用。

在大量谷歌搜索的帮助下,我终于找到了可行的选项。似乎要设置本地会话,您必须使用 DCOM 会话选项。

这是对我有用的代码:

var sessionOptions = new DComSessionOptions
{
    Timeout = TimeSpan.FromSeconds(30)
};
var cimSession = CimSession.Create("localhost", sessionOptions);

var volumes = cimSession.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");

foreach (var volume in volumes)
{
    Console.WriteLine(volume.CimInstanceProperties["Name"].Value);
}