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 theSystem.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 withthrow
, in which case the statement-terminating error turns into a script-terminating (thread-terminating) one.
- More typically, you'd choose to display the error (e.g. with
For a comprehensive overview of PowerShell's surprisingly complex error handling, see this GitHub docs issue.