title: Creating a persistent Powershell session in C#
body: <p>I have a project which calls a bunch of Powershell scripts, a few of which take several minutes to run through and cause the page to timeout. I thought about using Start-Job to run several processes in the background to free up the page from timing out, but each time I run a Powershell command it opens a new instance of Powershell and cannot find any jobs.</p>
  
  <pre><code>protected void RunShell()
  {
      var Shell = PowerShell.Create();
      Shell.Commands.AddScript(Textbox.Text);
      var results = Shell.Invoke();
      if (results.Count &gt; 0)
      {
          var builder = new StringBuilder();
          foreach (var psObject in results)
          {
              builder.AppendLine(psObject.BaseObject.ToString();
          }
          Textbox2.Text = builder.ToString();
       }
  }
  
  protected void button1_Click(object sender, EventAgrs e)
  {
      Textbox1.Text = "Start-Job -ScriptBlock{.\\script.ps1} | Out-String";
      RunShell();
  }
  
  protected void button2_Click(object sender, EventArgs e)
  {
      Textbox1.Text = "Get-Job * | Out-String";
      RunShell();
  }
  </code></pre>
  
  <p>I am now hoping to create a persistent session of powershell that I am able to send commands to and retrieve the jobs and statuses from. I cannot figure out how to set up this snippet of code as a global variable.</p>
  
  <p>Any pointers in the right direction would be appreciated.</p>