在C#中的Powershell返回命令输出
问题描述:
我是新来的C#和Powershell在一起,但我希望创建一个网页,在后端利用Powershell。我意识到我正在做的事情可以完全用C#完成,但是想知道其他应用程序。在C#中的Powershell返回命令输出
本质上,我从Web窗体中获取新的Web应用程序的名称并获取经过身份验证的用户的用户名以用于物理路径映射。
我的Powershell代码正常工作(即使直接从Pipeline.Commands [0]中复制它),但它在运行时似乎没有做任何事情。如果我强制使用一个结果变量(例如:make -physicalpath是一个不存在的路径),但在所有参数都正确的情况下,结果变量中会出现参数错误,则变量结果只包含一个空白项。
我看到很多类似的问题,但没有看到确切的答案。
这听起来像是C#或IIS Powershell模块问题吗?任何想法如何从我的命令中获得更多信息?
protected void Button1_Click(object sender, System.EventArgs e)
{
String username = getUser();
String physicalPath = "S:\\WebSites\\" + username + "\\public_html\\" + TextBox1.Text;
// Create Powershell Runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(
"Import-Module WebAdministration; set-psdebug -trace 1; " +
"New-WebApplication -Site MySite" +
" -Name " + TextBox1.Text +
" -PhysicalPath " + physicalPath +
" -ApplicationPool WebSites -Verbose -force");
pipeline.Commands.Add("Out-String");
// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// Close runspace
runspace.Close();
//Script results to string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
}
谢谢!
答
这看起来应该起作用。你应该检查错误流,看看有没有消息(即:“目标元素已经存在”)。
我会还建议你考虑使用PowerShell的2 API,作为在这个博客帖子:
http://huddledmasses.org/how-to-invoke-powershell-and-use-the-results-from-csharp/
如果你使用,你可以检查ps.Streams.Error以确保它是空的...
谢谢Jaykul - 我会给你一个尝试,当我有机会回来。 – user566175 2011-01-10 16:33:12