hoffimar
hoffimar

Reputation: 543

Access WMI instances via MI without WS-Management service

I'm trying to access WMI classes on Windows 7 and Windows 10 Embedded on localhost via the Microsoft.Management.Infrastructure API from C#. It works using the code from the below snippet, but only if I start the Windows Remote Management (WS-Management) service.

I noticed that I can access the classes via Powershell cmdlets like Get-WmiObject even when the WS-Management service is not started. Is there any way to access WMI without the service started via the Microsoft Management Infrastructure APIs?

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

Upvotes: 3

Views: 1681

Answers (2)

Rainmaker
Rainmaker

Reputation: 171

So, I came accross the same issue. To add to this, Windows.Management.Instrumentation is not available in .NET Core, but Microsoft.Management.Infrastructure is.

With the help of a lot of Googling, I finally found the options that work. It seems that to setup a local session, you have to use DCOM session options.

Here is the code that worked for me:

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

Upvotes: 6

NicoRiff
NicoRiff

Reputation: 4883

If you are workin locally then you should always be able to access WMI. From the MSDN documentation:

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.

You can also use ORMi (very simple to use) library for WMI for automatic mapping between WMI classes and C# models.

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

Then querying:

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

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

Upvotes: 1

Related Questions