title: Reading a ps1 file from C# / powershell and C# runspace
body: <p>I am trying to run the following simple ps1 file (which works fine if I call it from powershell) from Visual C#.</p>
  
  <hr>
  
  <p>[windowsErrorReporting.ps1]</p>
  
  <pre><code>    Get-WindowsErrorReporting
  
      if($WER_ENABLED -eq "True")
      {
          Enable-WindowsErrorReporting
      }
      else
      {
          Disable-WindowsErrorReporting
      }
  
      Get-WindowsErrorReporting // *1
  </code></pre>
  
  <p>The following is the C# code I wrote, and here is the situation I got:</p>
  
  <ul>
  <li>Suppose I turned off Windows Error Reporting from the C# runspace.</li>
  <li>When I turn it off from C#, the second Get-WindowsErrorReporting (the line I marked as *1 above)
  shows that the setting was properly changed.</li>
  <li>However, when I type Get-WIndowsErrorReporting on another powershell window, the value is still not changed.</li>
  <li>I also tried the other way around : Change the state from the powershell window, and check the state from the C# code... This time, I get "disabled" from the powershell window, and "enabled" from the C# runspace.
  <ul>
  <li>From what I saw, I guess there is no "Link" between the powershell "sessions"(sorry I don't know how they call it...) of the powershell window and C# runspace...</li>
  </ul></li>
  </ul>
  
  <hr>
  
  <pre><code>    private string RunScript(string scriptFileName)
      {
          // Read text data from the script file.
          string cmd;
          var assm = Assembly.GetExecutingAssembly();
          using (var stream = assm.GetManifestResourceStream("MyProject.Resources."+scriptFileName))
          {
              var reader = new StreamReader(stream);
              cmd = reader.ReadToEnd();
          }
  
          // create powershell runspace
          Runspace runspace = RunspaceFactory.CreateRunspace();
          // open it
          runspace.Open();
  
          // Create a pipeline and feed it the script text
          Pipeline pipeline = runspace.CreatePipeline();
          pipeline.Commands.AddScript(cmd);
  
          pipeline.Commands.Add("Out-String");
          foreach (string key in args.Keys)
          {
              runspace.SessionStateProxy.SetVariable("WER_ENABLED", "False");
          }
  
          Collection&lt;PSObject&gt; results;
          StringBuilder stringBuilder = new StringBuilder();
  
          // execute the script
          results = pipeline.Invoke();
  
          // convert the script result into a single string
          foreach (PSObject obj in results)
          {
               stringBuilder.AppendLine(obj.ToString());
          }
  
          // Close the runspace
          runspace.Close();
  
          // Return output
          return stringBuilder.ToString();
  
      }
  </code></pre>
  
  <hr>
  
  <p>I really appreciate if someone help me understand what is going on....</p>