Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture error output only in a variable in PowerShell

Tags:

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?

like image 894
Klas Mellbourn Avatar asked Jan 09 '15 13:01

Klas Mellbourn


People also ask

How do you catch specific errors in PowerShell?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

How do I get the output variable in PowerShell?

The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.

How do I cut output in PowerShell?

PowerShell Trim() methods (Trim(), TrimStart() and TrimEnd()) are used to remove the leading and trailing white spaces and the unwanted characters from the string or the raw data like CSV file, XML file, or a Text file that can be converted to the string and returns the new string.

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


2 Answers

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.

like image 190
arco444 Avatar answered Sep 18 '22 15:09

arco444


Here is simpler solution by Simon Wahlin using sub expressions

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

Would be:

$errOutput = $( $output = & $command $params ) 2>&1 
like image 45
Jim Avatar answered Sep 21 '22 15:09

Jim