To complement Frode F.'s helpful answer, which sensibly recommends modifying the script to use Write-Error
for error reporting:
If modifying the code is not an option and you're using PSv5+, you can capture Write-Host
output, because since PSv5 Write-Host
writes to the newly introduced information output stream (to which primarily Write-Information
is designed to write):
PowerShell's output streams are numbered, and the information stream has number 6
so that output-redirection expression 6>&1
redirects the information stream into the success output stream, whose number is 1
, allowing regular capturing in a variable, as the following example shows:
# PSv5+
$captured = Write-Host 'write-host output' 6>&1
$captured # output what was captured -> 'write-host output'
To learn more about PowerShell's output streams and redirection, run Get-Help about_Redirection
Note:
Write-Host
output captured via 6>&1
consists of one or more System.Management.Automation.InformationRecord
instances, which print as if they were strings, namely by their .MessageData.Message
property value, which is the string content of the argument(s) passed to Write-Host
.
Therefore, any coloring that stems from the use of the -ForegroundColor
and -BackgroundColor
parameters is not (directly) passed through:
However, the information is preserved, namely in the .MessageData.ForegroundColor
and .MessageData.BackgroundColor
properties, along with the information about whether -NoNewLine
was passed to Write-Host
, in Boolean property .MessageData.NoNewLine
This answer shows how to recreate the original coloring from the captured objects.
By contrast, coloring via ANSI / VT escape sequences embedded in the original string argument(s) is preserved.
Note: To capture the output and also pass it through (to the success output stream), you have two options:
Simply enclose the statement in (...)
, but note that output will only show after all output has been collected.
($captured = Write-Host 'write-host output' 6>&1)
For streaming pass-through, use Tee-Object
with the -Variable
parameter:
Write-Host 'write-host output' 6>&1 | Tee-Object -Variable captured
The above techniques generally work for capturing and passing success-stream output through, irrespective of whether redirections are involved.