title: Redirect powershell output and errors to console (in real-time) and to a variable
body: <p>I would like to redirect the output of a command in PowerShell, following these rules:</p>
  
  <ul>
  <li><p>The command is stored to a variable</p></li>
  <li><p>Output must be written to the console in real-time (i.e. "ping" results), including errors</p></li>
  <li><p>Output must be stored to a variable, including errors (real-time is not mandatory here)</p></li>
  </ul>
  
  <p>Here are my tests, assuming:</p>
  
  <pre><code>$command = "echo:"
  </code></pre>
  
  <p>to test errors redirection, and:</p>
  
  <pre><code>$command = "ping 127.0.0.1"
  </code></pre>
  
  <p>to test real-time output.</p>
  
  <ol>
  <li><p>Output is written in real-time, errors are not redirected at all</p>
  
  <pre><code>Invoke-Expression $command 2&gt;&amp;1 | Tee-Object -Variable out_content
  </code></pre></li>
  <li><p>Output is written in real-time, errors are only redirected to the console</p>
  
  <pre><code>Invoke-Expression ($command 2&gt;&amp;1) | Tee-Object -Variable out_content
  Invoke-Expression $command | Tee-Object -Variable out_content 2&gt;&amp;1
  </code></pre></li>
  <li><p>Output is not written in real-time, errors are correctly redirected to both</p>
  
  <pre><code>(Invoke-Expression $command) 2&gt;&amp;1 | Tee-Object -Variable out_content
  </code></pre></li>
  </ol>
  
  <p>Is it possible to get those rules working together?</p>