How can you programmatically turn off or on 'Windows Features' How can you programmatically turn off or on 'Windows Features' windows windows

How can you programmatically turn off or on 'Windows Features'


If you are only targeting newer platforms (>= Windows Vista) then dism.exe is the latest utility; it replaces pkgmgr.

  1. http://technet.microsoft.com/en-us/library/dd799309(WS.10).aspx
  2. http://msdn.microsoft.com/en-us/library/dd371719(v=vs.85).aspx

Example call (run for all required features):

dism.exe /online /enable-feature /featurename:IIS-WebServerRole

To find a feature, use this

dism.exe /online /get-features | find “Tablet”

see: http://adriank.org/microsoft-ocsetupdism-component-name-list/ for more info.


I do this using NSIS for IIS using :

$Sysdir\pkgmgr.exe /n:$Temp\iis7Unattend.xml

You can call the pkgmgr program from your c# program and usually you would create an unattend file with the instructions for the pkgmgr to use for the feature.

You need to use

 System.Diagnostics.Process.Start().


Using Microsoft.Dism

You could also use the Microsoft.Dism Nuget Package. It is a wrapper around the dismapi.dll, which is also used by the powershell cmdlets.

Install

To install via package manager console use.

Install-Package Microsoft.Dism

Installation via dotnet command line interface.

dotnet add package Newtonsoft.Json

Documentation

The NuGet pacakge has excelent xml documentation. Also see their Wiki for more information.And the DISM API Reference documentation from microsoft.

Examples

To get a list of all installed features:

IEnumerable<string> GetInstalledFeatures(){    var installedFeatures = new List<string>();    DismApi.Initialize(DismLogLevel.LogErrorsWarningsInfo);    try    {        using var session = DismApi.OpenOnlineSessionEx(new DismSessionOptions() { });        var features = DismApi.GetFeatures(session);        foreach (var feature in features)        {            if (feature.State == DismPackageFeatureState.Installed)                installedFeatures.Add(feature.FeatureName);        }    }    finally    {        DismApi.Shutdown();    }    return installedFeatures;}

To Enable a certain feature:

void EnableFeature(string featureName){    DismApi.Initialize(DismLogLevel.LogErrorsWarningsInfo);    try    {        using var session = DismApi.OpenOnlineSession();        var (left, top) = Console.GetCursorPosition();        DismApi.EnableFeature(session, featureName, false, true, null, progress =>        {            Console.SetCursorPosition(left, top);            Console.Write($"{progress.Total} / {progress.Current}");        });        Console.WriteLine();    }    finally    {        DismApi.Shutdown();    }}