检测Windows Server 2012上安装的服务器角色

时间:2013-03-23 01:14:19

标签: c# .net windows-server-2012

在Windows Server 2008中,您可以使用WMI和Win32_ServerFeature类以编程方式检测服务器功能和角色。

在Windows Server 2012中,不推荐使用Win32_ServerFeature类,并且不包含2012年新功能和新角色。

据我所知,Win32_ServerFeature类已由Server Manager Deployment替换,并且没有如何使用它的示例。

我在线搜索除了没有帮助的文档外,找不到任何信息。

任何帮助都会受到赞赏,我正在使用4.5 Dot Net Framework应用程序中的c#进行开发。

2 个答案:

答案 0 :(得分:8)

我考虑这样做的方法是使用一段PowerShell脚本,然后在C#中“播放”输出。

如果您添加对以下项目的引用,您将能够与C#中的PowerShell脚本进行交互:

  

System.Management.Automation

然后使用以下使用语句深入研究并与之相互作用:

using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces

以下脚本将创建一个很好的sub,它将接受PowerShell命令并返回一个可读字符串,每个项目(在本例中为一个角色)作为新行添加:

private string RunScript(string scriptText)
{
// create a Powershell runspace then open it

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

// create a pipeline and add it to the text of the script

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);

// format the output into a readable string, rather than using Get-Process
// and returning the system.diagnostic.process

pipeline.Commands.Add("Out-String");

// execute the script and close the runspace

Collection<psobject /> results = pipeline.Invoke();
runspace.Close();

// convert the script result into a single string

StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}

return stringBuilder.ToString();
}

然后,您可以将以下PowerShell命令传递给脚本并接收输出,如下所示:

RunScript("Import-module servermanager | get-windowsfeature");

或者,您可以从C#脚本运行此PowerShell命令,然后在脚本完成处理后从C#读取输出文本文件:

import-module servermanager | get-windowsfeature > C:\output.txt

希望这有帮助!

答案 1 :(得分:1)

我建议您检查Windows注册表。例如,对于IIS组件,您可以检查HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\Components文件夹