Check if WMI is enabled

StewartBW 505 Reputation points
2024-04-06T12:44:29.2366667+00:00

Hello

Using this code:

Using Search As New ManagementObjectSearcher(New SelectQuery("Win32_Processor"))

For Each Info As ManagementObject In Search.Get

Will throw exceptions if Winmgmt service is disabled on the user's system.

I need to check if the underlying service is disabled and prevent the exception, instead show a message and terminate the rest of code.

If Search Is Nothing... will not work, how do I check?

Thanks.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,381 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,605 questions
{count} votes

Accepted answer
  1. Marcin Policht 13,715 Reputation points MVP
    2024-04-06T13:40:15.6+00:00

    Try the following:

    using System;
    using System.ServiceProcess;
    class Program
    {
        static void Main()
        {
            // Name of the WMI service
            string serviceName = "winmgmt";
            // Check if the service is installed
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController service in services)
            {
                if (service.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase))
                {
                    // Check if the service is running and its start type
                    Console.WriteLine($"Service Name: {service.ServiceName}");
                    Console.WriteLine($"Status: {service.Status}");
                    Console.WriteLine($"Start Type: {service.StartType}");
                    return;
                }
            }
        }
    }
    
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. StewartBW 505 Reputation points
    2024-04-06T14:38:21.8033333+00:00

    Thanks,

    Shorter: New ServiceController("Winmgmt").Status

    But what about "HKLM\SYSTEM\CurrentControlSet\Services\Winmgmt" > "Start" ?

    If value = 4 means disabled, the only question would be that which value to use as default?

    Using MyKey As RegistryKey = Registry.LocalMachine.OpenSubKey("HKLM\SYSTEM\CurrentControlSet\Services\Winmgmt", False)
    If MyKey IsNot Nothing Then
    MyKey.GetValue("Start", DefaultValue???)
    

    How do you think about DefaultValue???