How to capture error messages specified by a command?

I am writing a PowerShell script where I need to write an error message that it throws. Note: according to PowerShell, there are no errors, and the command completed successfully.

For example: I tried to download the package from SVN Link. The link is actually not. The script shows me an error message on the console. However, when did I try to check $_ or $? or $error , I did not see any error messages. However, $LASTEXITCODE returns a value of 1. I need to get the exact error message.

+5
source share
3 answers

If you get an error message, you need to catch the error stream:

 $msg = command 2>&1 

or

 command 2>error.txt 

PowerShell writes its messages to different streams, which can be redirected to files to capture the corresponding output.

  • Stream 1 (default): normal output ("STDOUT")
  • Stream 2: error messages ("STDERR"), including error messages from external programs
  • Stream 3: Warning Messages
  • Stream 4: detailed messages
  • Stream 5: Debugging Messages
  • Stream 6: Informational Messages (PowerShell v5 and later only)

To capture a specific stream in a file, you need to redirect the stream number to the file name. for instance

 command 2>"C:\path\to\error.log" 

will record all error messages created by command in the file C:\path\to\error.log . Use 2>> instead of 2> if you want to add a file, and not overwrite it every time you start.

You can also combine other threads with STDOUT to process / redirect the entire command:

 command >>"C:\path\to\all.log" *>&1 

See Get-Help about_Redirection or this Scripting Guy article for more information on streams and redirection.

Things worth noting:

  • Redirection *> appeared in PowerShell v3, so it will not work in PowerShell v2 and earlier versions.
  • A new thread appeared in PowerShell v5 ( Information , thread No. 6), because people continued to abuse Write-Host because they did not understand what the cmdlet was intended for.
+20
source

Assuming your executable is named svn.exe and is on the way, you can capture the messages it sends to the console as follows:

 $msg = [string] (svn.exe <your parameters here>) 

You can then parse the $ msg line to find the information you need.

+5
source

Inspired by David Brabants answer , you can combine both stdout and stderr into a single array of strings using this command:

 $output = [string[]] (.\Cli.exe -p $param 2>&1) 

It will execute Cli.exe with the p parameter. It's not obligatory.

Explanation

2>&1 means that stream # 2 (stderr) will be redirected to stream # 1 (stdout), so both streams will go to $output .

+1
source

Source: https://habr.com/ru/post/1489230/


All Articles