title: Capture standart output of powershell script executed from .NET application
body: <p>Let's assume that I have very simple powershell script <code>myscript.ps1</code>, which writes to standart output:</p>
  
  <pre><code>get-location
  </code></pre>
  
  <p>Now I want to execute this script from .net application. I ended up with next code:</p>
  
  <pre><code>var process = new Process
          {
              StartInfo = {
                  FileName = "powershell.exe",
                  Arguments = "-file \"myscript.ps1\"",
                  WorkingDirectory = Path.Combine(Environment.CurrentDirectory, "run"),
                  UseShellExecute = false,
                  RedirectStandardOutput = true
              }
          };
  
  process.OutputDataReceived += (sender, args) =&gt; Console.WriteLine(args.Data);
  process.Start();
  process.BeginOutputReadLine();
  process.WaitForExit();
  </code></pre>
  
  <p>And it works, but I think it should be more elegant way to do it using <code>System.Management.Automation</code> assembly:</p>
  
  <pre><code>using (PowerShell shell = PowerShell.Create())
  {
      shell.Commands.AddScript("myscript.ps1");
      var r = shell.Invoke();
      Console.WriteLine(r);
  }
  </code></pre>
  
  <p>But <code>Invoke</code> returns collection of `PSObject, and I can't find way to get access to stdout</p>