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:$badoutput
will now contain the contents of the error string.To add to arco444, the specific exception can be obtained by using
$badoutput[0].Exception
.-ErrorAction and -ErrorVariable has more information on to effectively use the ErrorAction and ErrorVariable parameters built into PowerShell.
Here is the easiest way to show this working:
Now one thing that is not obvious to people is that you can specify a “+” in front of the variable name for ErrorVariable and we will ADD the errors to that variable.
Lastly, you don’t need to type out –ErrorAction or –ErrorVariable, we have defined parameter aliases for these so you can just type
–EA
and-EV
.