Powershell in C# Return Command Output
I'm new to bringing C# and Powershell together, but am hoping to create a web page that leverages Powershell in the back end. I realize that what I am doing can be done solely with C#, but would like to figure this out for other applications.
Essentially, I am taking the name of a new web application from a web form and getting the authenticated user's username for physical path mapping.
My Powershell code works correctly (even when copying it from Pipeline.Commands[0] directly), but it does not appear to do anything when I run it. I get parameter errors in the resu开发者_如何学Clt variable if I force one (ex: make -physicalpath a non-existent path), but with all parameters correct, the variable result only contains one blank item.
I see many similar questions to this one, but do not see s definitive answer.
Does this sound like a C# or IIS Powershell module issue? Any ideas how I get more information returned from my command?
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());
}
}
Thanks!
That looks like it should work. You should check the error stream and see if there are messages there (ie: "Destination element already exists").
I'd also suggest you consider using the PowerShell 2 APIs as in this blog post:
http://huddledmasses.org/how-to-invoke-powershell-and-use-the-results-from-csharp/
If you're using that, you can check the ps.Streams.Error to make sure it's empty...
精彩评论