Redirecting Streams

by Jul 17, 2020

PowerShell writes output information to six different streams, and only the output stream is assigned to variables:

function Invoke-Test
{
  "Regular Output"
  Write-Host "You always see me!"
  Write-Information "Info"
  Write-Warning "Warning"
  Write-Error "Error"
  Write-Debug "Debug"
  Write-Verbose "Verbose"
  Write-Output "Output"
}

$result = Invoke-Test

All the remaining streams either show in the console, or are hidden, depending on the setting of their appropriate preference variable:

 
PS> Get-Variable -Name *preference -Exclude *confirm*,*whatif*,*progress*

Name                           Value
----                           -----
DebugPreference                SilentlyContinue
ErrorActionPreference          Continue
InformationPreference          SilentlyContinue
VerbosePreference              SilentlyContinue
WarningPreference              Continue     
 

Occasionally, it may be required to also capture the output of other streams and process it rather than outputting it to the console. For this, you can redirect all streams to the output stream and capture the total result in a variable:

function Invoke-Test
{
  "Regular Output"
  Write-Host "You always see me!"
  Write-Information "Info"
  Write-Warning "Warning"
  Write-Error "Error"
  Write-Debug "Debug"
  Write-Verbose "Verbose"
  Write-Output "Output"
}


$all = Invoke-Test *>&1

This variable now contains the combined output of all streams. In order to process the streams individually, you may want to group the content by type:

 
PS> $groups = $all | Group-Object -Property { $_.GetType().Name } -AsHashTable -AsString 

PS> $groups

Name                           Value
----                           -----
WarningRecord                  {Warning}
InformationRecord              {You always see me!, Info}                                                                         
ErrorRecord                    {Error}
String                         {Regular Output, Output}


PS> $groups.WarningRecord
WARNING: Warning

PS> $groups.InformationRecord
You always see me!
Info 
 


Twitter This Tip! ReTweet this Tip!