How to capture error output only in a variable in PowerShell

I want to store the stderr output of a PowerShell command in a variable. I don't want to store it in a file and I don't want standard output included, just the error output.

This redirects to a file named error.txt:

& $command $params 2> error.txt

This redirects both stderr and stdout to the $output variable:

$output = & $command $params 2>&1

But I want to store only the error output in a variable (the same as the content of the error.txt file above), without writing anything to file. How do I do that?


  • You can call the command a slightly different way and use the -ErrorVariable parameter in PowerShell:

    Invoke-Expression "$command $params" -ErrorVariable badoutput

    $badoutput will now contain the contents of the error string.