以编程方式启用IIS角色和功能

3

我正在尝试通过c#控制台应用程序启用IIS功能。在Windows 7和Windows 8.1计算机上运行良好,但在Windows Server 2008 R2和Windows Server 2012 R2上运行相同的代码时不起作用。我在这段代码中漏掉了什么?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text.RegularExpressions;

namespace EnableIISComponents
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SetupIIS();
                Console.WriteLine("Done. Press any key to close.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred:" + ex.Message);
            }
            Console.ReadLine();
        }
    static string SetupIIS()
    {
        // In command prompt run this command to see all the features names which are equivalent to UI features.
        // c:\>dism /online /get-features /format:table 
        var featureNames = new List<string> 
                {
                    "IIS-ApplicationDevelopment",                        
                    "IIS-ISAPIExtensions",
                    "IIS-ISAPIFilter",
                    "IIS-CommonHttpFeatures",
                    "IIS-DefaultDocument",
                    "IIS-HttpErrors",
                    "IIS-StaticContent",
                    "IIS-HealthAndDiagnostics",
                    "IIS-HttpLogging",
                    "IIS-HttpTracing",
                    "IIS-WebServer",
                    "IIS-WebServerRole",
                    "IIS-ManagementConsole",
                };

        Console.WriteLine("Checking the Operating System...\n");

        ManagementObjectSearcher obj = new ManagementObjectSearcher("select * from Win32_OperatingSystem");
        try
        {
            foreach (ManagementObject wmi in obj.Get())
            {
                string Name = wmi.GetPropertyValue("Caption").ToString();

                // Remove all non-alphanumeric characters so that only letters, numbers, and spaces are left.
                // Imp. for 32 bit window server 2008
                Name = Regex.Replace(Name.ToString(), "[^A-Za-z0-9 ]", "");

                if (Name.Contains("Server 2012 R2") || Name.Contains("Windows 81"))
                {
                    featureNames.Add("IIS-ASPNET45");
                    featureNames.Add("IIS-NetFxExtensibility45");
                }
                else if (Name.Contains("Server 2008 R2") || Name.Contains("Windows 7"))
                {
                    featureNames.Add("IIS-ASPNET");
                    featureNames.Add("IIS-NetFxExtensibility");
                }
                else
                {
                    featureNames.Clear();
                }

                string Version = (string)wmi["Version"];
                string Architecture = (string)wmi["OSArchitecture"];

                Console.WriteLine("Operating System details:");
                Console.WriteLine("OS Name: " + Name);
                Console.WriteLine("Version: " + Version);
                Console.WriteLine("Architecture: " + Architecture + "\n");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred:" + ex.Message);
        }

        return Run(
            "dism",
            string.Format(
                "/NoRestart /Online /Enable-Feature {0}",
                string.Join(
                    " ",
                    featureNames.Select(name => string.Format("/FeatureName:{0}", name)))));
    }

    static string Run(string fileName, string arguments)
    {
        Console.WriteLine("Enabling IIS features...");
        Console.WriteLine(arguments);

        using (var process = Process.Start(new ProcessStartInfo
        {
            FileName = fileName,
            Arguments = arguments,
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardOutput = true,
            UseShellExecute = false,
        }))
        {
            process.WaitForExit();
            return process.StandardOutput.ReadToEnd();
        }
    }

}
}

如果我通过命令提示符运行具有相同featureNames的dism命令,则可以启用IIS功能,而不是在服务器上运行此程序。为什么程序不能正常工作?
我通过右键单击并选择“以管理员身份运行”来以管理员身份运行我的程序。
我从以下链接中获取帮助创建了这个示例。 更好的程序化安装IIS7的方法

我已经编译了你的代码,并在全新的Server 2012 R2上测试通过。请检查未能正常运行的服务器的dism日志C:\Windows\Logs\DISM\dism.log - Peter Hahndorf
1个回答

3
最终我找到了原因。 在项目属性中,目标平台是“任何 CPU”,但“优先使用 32 位”选项被勾选了。这导致了问题。 在 Server 2012 R2 中,我的应用程序尝试使用 32 位版本的 DISM。这就是问题所在。 一旦我取消了该选项,它就可以正常工作了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接