title: Powershell redirect std error to variable
body: <p>I would like to invoke an arbitrary expression and redirect std error to a variable without redirection to a file.</p>
  
  <p>For example, in Powershell it is possible to redirect standard error <a href="https://technet.microsoft.com/en-us/library/hh847746.aspx" rel="nofollow noreferrer">using 2> operator</a>. Using a temporary file, I can easily get what I want:</p>
  
  <pre><code>#$expr = "1/0"                          # with std error
  #$expr = "2+2"                          # without stderror
  #$expr = "Get-Service invalidsvc"       # with stderror
  $expr = "try { throw '111' } catch { }" # without std error
  $ans = Invoke-Expression $expr -ErrorVariable ev 2&gt; C:\log\stderr.txt
  if(cat C:\log\stderr){
      Write-Host "Error $ev"    
  }
  </code></pre>
  
  <p>How can I do the same, but without creation of a temporal output file?</p>
  
  <p>Wrong solutions:</p>
  
  <ol>
  <li><p>Using -ErrorVariable switch. Counter example:</p>
  
  <p>Invoke-Expression $expr -ErrorVariable ev 2> C:\aaa\file1.txt
  $expr = "try { throw '111' } catch { }"
  Write-Host "Error $ev" # will output error, but std error is empty</p></li>
  <li><p>$LASTEXITCODE and $? check. Counter example:</p>
  
  <p>Get-Service invalidservice</p></li>
  </ol>
  
  <p>$lastexitcode is equal to 0, $? is equal to True, but std error is not empty</p>
  
  <p>The idea is simple: save the "red" (std error) text in Powershell console in a variable. The command I receive is an arbitrary string.
  Examples:</p>
  
  <ol>
  <li><p>When I write "try { throw '111' } catch { }" in Powershell console there will be no red (error) text in PS console (despite the fact $error is not empty). So if I invoke that expression in my code I get no error saved in some variable.</p></li>
  <li><p>When I write "Get-Service notexistingservice", or "1/0", or "Write-Error 111" there will red (error) text and non-null $error. So if I invoke that expression in my code I would like to get error saved in some variable.</p></li>
  </ol>