title: Powershell in C# Return Command Output
body: <p>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.  </p>
  
  <p>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. </p>
  
  <p>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 result 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. </p>
  
  <p>I see many similar questions to this one, but do not see s definitive answer.   </p>
  
  <p>Does this sound like a C# or IIS Powershell module issue?  Any ideas how I get more information returned from my command?  </p>
  
  <pre><code>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&lt;PSObject&gt; results = new Collection&lt;PSObject&gt;();
    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());
    }
  
  }
  </code></pre>
  
  <p>Thanks!</p>