title: Exceptions swallowed when capturing Invoke-Expression output and redirecting stderr
body: <p>I want to capture and log all output (redirecting stderr) from Invoke-Expression calls, but by doing that any exception that would normally be thrown seems to be swallowed.</p>
  
  <p>Assuming c:\temp\test already exists this command will throw an exception:</p>
  
  <pre><code>PS U:\&gt; $cmd = "mkdir c:\temp\test"
  PS U:\&gt; $output = Invoke-Expression $cmd
  New-Item : Item with specified name C:\temp\test already exists.
  At line:38 char:24
  +         $scriptCmd = {&amp; &lt;&lt;&lt;&lt;  $wrappedCmd -Type Directory @PSBoundParameters }
      + CategoryInfo          : ResourceExists: (C:\temp\test:String) [New-Item], IOException
      + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
  </code></pre>
  
  <p>But, if I redirect stderr, then nothing happens:</p>
  
  <pre><code>PS U:\&gt; $cmd = "mkdir c:\temp\test 2&gt;&amp;1"
  PS U:\&gt; $output = Invoke-Expression $cmd
  PS U:\&gt;
  </code></pre>
  
  <p>This is a simplified example, and I'm using Invoke-Expression in a function for many types of calls, and logging the output. So it is not just a matter of making this call work.</p>
  
  <p>Furthermore not capturing the output will also throw the exception correctly:</p>
  
  <pre><code>PS U:\&gt; $cmd = "mkdir c:\temp\test 2&gt;&amp;1"
  PS U:\&gt; Invoke-Expression $cmd
  New-Item : Item with specified name C:\temp\test already exists.
  At line:38 char:24
  +         $scriptCmd = {&amp; &lt;&lt;&lt;&lt;  $wrappedCmd -Type Directory @PSBoundParameters }
      + CategoryInfo          : ResourceExists: (C:\temp\test:String) [New-Item], IOException
      + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
  </code></pre>
  
  <p>I see that $Error actually contains the exception, but I don't know if I can be sure that it contains only errors related to the Invoke-Expression call.</p>
  
  <p>But the question stands. How can I capture all output (including stderr) from Invoke-Expression, and still get exceptions thrown?</p>