How do I programmatically find out if a windows feature is enabled or not?

  Kiến thức lập trình

I need to be able to determine if a windows feature has been enabled or not. From digging around and a lot of searching I came up with some code so I can find the windows feature as shown below:

ManagementClass objMC = new ManagementClass("Win32_OptionalFeature");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
    string featureName = (string)objMO.Properties["Caption"].Value;

    if (featureName.ToLower().Contains("websocket"))
    {
        // now where do i get the info on if its enabled??
        Console.WriteLine($"Feature Name: {featureName}");
    }
}

However I have not been able to determine whether or not this feature is enabled or not. What am I missing?

Thanks!

1

You can use Powershell for this.

In Powershell this would be simply

Get-WindowsOptionalFeature -Online -FeatureName *websocket*

In C#, you can create a runspace and add that command.

var features = PowerShell.Create()
    .AddCommand("Get-WindowsOptionalFeature")
    .AddParameter("Online")
    .AddParameter("FeatureName", featureWildcard)
    .Invoke();

Then you can look at the State property to see if it’s enabled.

Note that this needs elevation.

1

Charlieface has an answer using PowerShell.

If you want to use code that’s similar to yours, look at the InstallState property on the object. From the Win32_OptionalFeature class documentation:

Properties

The Win32_OptionalFeature class has these properties.

[…]

InstallState

Data type: uint32

Access type: Read-only

Identifies the state of the optional feature. The following states are possible:

Enabled (1)

Disabled (2)

Absent (3)

Unknown (4)

[…]

ManagementClass objMC = new("Win32_OptionalFeature");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
    string featureName = (string)objMO.Properties["Caption"].Value;
 
    if (featureName.ToLower().Contains("websocket"))
    {
        bool isEnabled = objMO.Properties["InstallState"].Value.ToString() == "1";
        Console.WriteLine($"Feature Name: {featureName} (Enabled: {isEnabled})");
    }
}

You can simplify this by using a ManagementObjectSearcher:

string query = """
    SELECT * 
    FROM Win32_OptionalFeature 
    WHERE Caption LIKE '%websocket%' 
        AND InstallState = 1
    """;
ManagementObjectSearcher objSearcher = new(query);
ManagementObjectCollection objMOC = objSearcher.Get();
foreach (ManagementObject objMO in objMOC)
{
    // All features in the collection are enabled because the query
    // has a filter on the "InstallState" property.
    string featureName = (string)objMO["Caption"];
    Console.WriteLine($"{featureName} is enabled");
}

This approach shouldn’t need elevation (at least in my testing it does not).

1

LEAVE A COMMENT