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

标签 c# .net windows wmi

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

我注意到即使 WS-Management 服务未启动,我也可以通过 Get-WmiObject 等 Powershell cmdlet 访问这些类。如果没有通过 Microsoft 管理基础结构 API 启动服务,是否有任何方法可以访问 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());
}

最佳答案

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

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

这是对我有用的代码:

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);
}

关于c# - 在没有 WS-Management 服务的情况下通过 MI 访问 WMI 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50761549/

相关文章:

c# - 从 IronPython 实例化自定义 C# 类

c# - x :TypeArguments 中的可空类型

c# - 非托管异常

.net - 为什么 IpcChannel 告诉我, "Cannot open an anonymous level security token?"

windows - 如何以编程方式设置文件标签

c# - 我可以为元组中的一项返回空值吗?

c# - 需要有关 LINQ to SQL WHERE-clause on foreign table 的帮助

.net - 两个被同一个对象锁定的 SyncLocked 代码块可以同时执行吗?

c++ - com 如何提供与语言无关的数据类型

c - 进程 Hook 问题