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

Dan*_*een 8 .net c# windows-server-2012

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

在Windows Server 2012中,Win32_ServerFeature类已被弃用,不包括2012年新增的功能和角色.

据我所知,Win32_ServerFeature类已被服务器管理器部署取代,并且没有如何使用它的示例.

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

任何帮助将不胜感激,我在4.5 Dot Net Framework应用程序中使用c#进行开发.

小智 8

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

如果添加对以下项的引用,则可以在C#中与PowerShell脚本进行交互:

System.Management.Automation

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

using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces
Run Code Online (Sandbox Code Playgroud)

以下脚本将创建一个很好的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();
}
Run Code Online (Sandbox Code Playgroud)

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

RunScript("Import-module servermanager | get-windowsfeature");
Run Code Online (Sandbox Code Playgroud)

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

import-module servermanager | get-windowsfeature > C:\output.txt
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!