Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write to standard error in PowerShell?

I'm having trouble figuring out how to both echo to the standard error stream and redirect the error stream of an executable.

I have come from a Bourne shell and Korn shell background, of which I would use;

# Write to stderr echo "Error Message!" >&2  # Redirect stderr to file /do/error 2>/tmp/err.msg 
like image 876
Brett Ryan Avatar asked Feb 14 '11 22:02

Brett Ryan


People also ask

How do you write error messages in PowerShell?

To write a non-terminating error, enter an error message string, an ErrorRecord object, or an Exception object. Use the other parameters of Write-Error to populate the error record. Non-terminating errors write an error to the error stream, but they do not stop command processing.

How do you use error variables in PowerShell?

Error variable in PowerShell is to view the errors generated in the current PowerShell session. We can say that the $Error variable is the container that stores all the errors and the latest error will be displayed first.

How do you handle errors in PowerShell script?

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.

What is the use of $_ in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3. 0; Usage information found here) which represents the current item from the pipe. PowerShell (v6. 0) online documentation for automatic variables is here.


2 Answers

Use Write-Error to write to stderr. To redirect stderr to file use:

 Write-Error "oops" 2> /temp/err.msg 

or

 exe_that_writes_to_stderr.exe bogus_arg 2> /temp/err.msg 

Note that PowerShell writes errors as error records. If you want to avoid the verbose output of the error records, you could write out the error info yourself like so:

PS> Write-Error "oops" -ev ev 2>$null PS> $ev[0].exception oops 

-EV is short (an alias) for -ErrorVariable. Any errors will be stored in the variable named by the argument to this parameter. PowerShell will still report the error to the console unless we redirect the error to $null.

like image 167
Keith Hill Avatar answered Sep 26 '22 18:09

Keith Hill


You probably want this:

$host.ui.WriteErrorLine('I work in any PowerShell host') 

You might also see the following, but it assumes your PowerShell host is a console window/device, so I consider it less useful:

[Console]::Error.WriteLine('I will not work in the PowerShell ISE GUI') 
like image 38
Chris Sears Avatar answered Sep 24 '22 18:09

Chris Sears