【发布时间】:2014-04-02 16:37:17
【问题描述】:
我编写了一个使用 Powershell API 安装 Windows 角色和功能的应用程序。它在 Windows 2008 R2 中运行良好,但在 Windows 2012 中没有任何反应;程序继续运行,好像一切正常,但没有安装任何东西。
我尝试将程序制作为 .NET v4.5(它是 .NET v2.0),但这并没有帮助。我一直在谷歌这件事上,我找不到有效的解决方案。事实上,大多数人说要使用适用于 Windows 2008 R2 的那种实现。这是我的代码:
public bool runPowerShell(string command, string args)
{
mLogger myLogger = mLogger.instance; //How I log stuff in my application.
bool done = false; //default Return value.
const string path = @"C:\\XMPLogs\\Roles and Features"; //Where Powershell output will go.
//Make sure Powershell log directory is there.
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
//Start a new Powershell instance.
PowerShell powershell = PowerShell.Create();
System.Collections.ObjectModel.Collection<PSObject> output = new System.Collections.ObjectModel.Collection<PSObject>();
StringBuilder strBuilder = new StringBuilder(); //Used to examine results (for testing)
powershell.AddScript(@"Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted");
powershell.AddScript(@"Import-Module ServerManager");
//powershell.Invoke();
powershell.AddScript(command + " " + args);
try
{
output = powershell.Invoke();
// Construct a StringBuilder to examine the output of Invoke()
foreach (PSObject obj in output)
strBuilder.AppendLine(obj.ToString());
// Show the StringBuilder to see results (always empty!)
MessageBox.Show(strBuilder.ToString());
done = true;
}
catch (Exception ex)
{
string test = ex.ToString();
MessageBox.Show(test);
myLogger.output("ERRO", "PowerShell command " + command
+ "failed to run with arguments \"" + args + "\". Message: " + ex.ToString());
done = false;
}
powershell.Dispose();
return done;
}
我会这样调用方法:
runPowerShell("add-windowsfeature", "-name FS-FileServer -logpath \"c:\\XMPLogs\\Roles and Features\\File Services.log\"");
“输出”对象中没有任何数据,日志文件也没有。所以,我不知道发生了什么。我确实知道,如果我在方法调用中获取两个参数并手动将它们输入到 Powershell 提示符中,安装就会完美运行。
谁能看到我在 Windows Server 2012 上的这个实现有什么问题?
谢谢。
【问题讨论】:
标签: c# powershell windows-server-2012