Home > other >  How to capture stdout and stderr both in one variable in powershell?
How to capture stdout and stderr both in one variable in powershell?

Time:10-06

I have tried so many things suggested in many discussions across SO and other sites to no avail. Here is my command that I am trying to capture full output of in a variable.

Invoke-WebRequest -Method Post -Uri http://www.google.com

Here is how I tried doing it (one of the many ways)

$output1 = & Invoke-WebRequest -Method Post -Uri http://www.google.com 2>&1

It continues to show the stderr output in the console and captures nothing in the variable. I have also tried Out-String and Tee-Object

What am I doing wrong?

CodePudding user response:

What your Invoke-WebRequest call emits is a statement-terminating error, which cannot be captured with 2>redirections.

  • 2> only works with non-terminating PowerShell errors and stderr output from external programs.

To catch terminating errors you need a try { ... } catch { .. . } statement:

$output1 = 
  try   { Invoke-WebRequest -Method Post -Uri http://www.google.com } 
  catch { $_ }
  • Inside the catch block, the automatic $_ variable contains the System.Management.Automation.ErrorRecord describing the terminating error that occurred.

  • By implicitly outputting it, it is sent to PowerShell's success output stream, and therefore stored in variable $output1.

    • More typically, you'd choose to display the error (e.g. with $_ | Write-Error, which emits it as a non-terminating one) or re-throw it with throw, in which case the statement-terminating error turns into a script-terminating (thread-terminating) one.

For a comprehensive overview of PowerShell's surprisingly complex error handling, see this GitHub docs issue.

  • Related