title: System.InvalidProgramException when trying to run Powershell commands in C#
body: <p>I have ran a debug stepping through the program and it crashes at the following line</p>
  
  <pre><code>Runspace runspace = RunspaceFactory.CreateRunspace();
  </code></pre>
  
  <p>It gives the following error  </p>
  
  <pre><code>An unhandled exception of type 'System.InvalidProgramException' occurred in     PrimarySMTP_Fix.exe
  
  Additional information: Common Language Runtime detected an invalid program.
  </code></pre>
  
  <p>This is my first time working with Power Shell through C# and I'm having trouble getting some simple code execution. The point of the project is to automate a simple fix for a common issue with our company's exchange server. </p>
  
  <p>The complete code is below. </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Windows;
  using System.Windows.Controls;
  using System.Windows.Data;
  using System.Windows.Documents;
  using System.Windows.Input;
  using System.Windows.Media;
  using System.Windows.Media.Imaging;
  using System.Windows.Navigation;
  using System.Windows.Shapes;
  using System.Management.Automation;
  using System.Collections.ObjectModel;
  using System.Management.Automation.Runspaces;
  
  
  namespace PrimarySMTP_Fix
  {
  
  public partial class MainWindow : Window
  {
      //Variable Declarations
      string userName = "";
      string confirmUser = "";
      string primarySMTP = "";
      string confirmSMTP = "";
  
  
      public MainWindow()
      {
          InitializeComponent();
      }
  
      private string RunScript(string scriptText)
      {
          Runspace runspace = RunspaceFactory.CreateRunspace();
          runspace.Open();
  
          Pipeline pipeline = runspace.CreatePipeline();
          pipeline.Commands.AddScript(scriptText);
  
          pipeline.Commands.Add("Out-String");
  
          Collection&lt;PSObject&gt; results = pipeline.Invoke();
  
          runspace.Close();
  
          StringBuilder stringBuilder = new StringBuilder();
          foreach (PSObject obj in results)
          {
              stringBuilder.AppendLine(obj.ToString());
          }
          return stringBuilder.ToString();
      }
  
      private void Button_Click(object sender, RoutedEventArgs e)
      {
          userName = adUser.Text;
          confirmUser = confirmAD.Text;
          primarySMTP = mail.Text;
          confirmSMTP = confirmMail.Text;
  
          outPut.Text = RunScript(userName);
  
  
      }
  }
  }
  </code></pre>
  
  <p>The above is just setup to test. For now it's taking just the username information and running it directly as a command. If I can get that to work and output information then I can re-write it to do what I want it to do. </p>