检测Windows Server 2012上安装了哪些服务器角色

问题描述 投票:8回答:2

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

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

据我所知,Win32_ServerFeature类已被Server Manager Deployment替代,没有使用方法的示例。

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

可以提供任何帮助,我正在c#中开发一个4.5 Dot Net Framework应用程序。

c# .net windows-server-2012
2个回答
8
投票
如果添加对以下项目的引用,您将能够与C#中的PowerShell脚本进行交互:

系统管理自动化

然后使用以下

using语句深入研究此功能并与之交互:

using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces 以下脚本将创建一个不错的子目录,该子目录将接受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
投票
© www.soinside.com 2019 - 2024. All rights reserved.