Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

powershell - How to capture error messages thrown by a command?

I am writing a PowerShell script where in I need to capture the error message that it's throwing. Note: according to PowerShell, there is no error and command is executed successfully.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

$msg = command 2>&1

or

command 2>error.txt

PowerShell writes its messages to different streams that can be redirected to files for capturing the respective output.

  • Stream 1 (default): regular output ("STDOUT")
  • Stream 2: error messages ("STDERR"), including error messages from external programs
  • Stream 3: warning messages
  • Stream 4: verbose messages
  • Stream 5: debug messages
  • Stream 6: information messages (only PowerShell v5 and newer)

To capture a particular stream in a file you need to redirect the stream number to a file name. For instance

command 2>"C:pathoerror.log"

would capture all error messages produced by command in the file C:pathoerror.log. Use 2>> instead of 2> if you want to append to the file instead of overwriting it with each run.

You can also combine other streams with STDOUT to process/redirect all command output:

command >>"C:pathoall.log" *>&1

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

Things worth of note:

  • The *> redirection was introduced with PowerShell v3, hence it won't work in PowerShell v2 and earlier.
  • PowerShell v5 introduced a new stream (Information, stream number 6) since people kept misusing Write-Host because they didn't understand what the cmdlet was intended for.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...