Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 6th, 2012  |  syntax: None  |  size: 1.12 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Powershell in C# Return Command Output
  2. protected void Button1_Click(object sender, System.EventArgs e)
  3. {
  4.   String username = getUser();
  5.   String physicalPath = "S:\WebSites\" + username + "\public_html\" + TextBox1.Text;
  6.  
  7.   // Create Powershell Runspace
  8.   Runspace runspace = RunspaceFactory.CreateRunspace();
  9.  
  10.   runspace.Open();
  11.  
  12.   // Create pipeline and add commands
  13.   Pipeline pipeline = runspace.CreatePipeline();
  14.   pipeline.Commands.AddScript(
  15.     "Import-Module WebAdministration; set-psdebug -trace 1; " +
  16.  
  17.     "New-WebApplication -Site MySite" +
  18.     " -Name " + TextBox1.Text +
  19.     " -PhysicalPath " + physicalPath +
  20.     " -ApplicationPool WebSites -Verbose -force");
  21.  
  22.   pipeline.Commands.Add("Out-String");
  23.  
  24.   // Execute Script
  25.   Collection<PSObject> results = new Collection<PSObject>();
  26.   try
  27.   {
  28.     results = pipeline.Invoke();
  29.   }
  30.   catch (Exception ex)
  31.   {
  32.     results.Add(new PSObject((object)ex.Message));
  33.   }
  34.  
  35.   // Close runspace
  36.   runspace.Close();
  37.  
  38.   //Script results to string
  39.   StringBuilder stringBuilder = new StringBuilder();
  40.   foreach (PSObject obj in results)
  41.   {
  42.     stringBuilder.AppendLine(obj.ToString());
  43.   }
  44.  
  45. }