2

I'm looking for the equivalent of the PowerShell pipeline redirection *>&1 when running a job.

I run the jobs roughly like this:

    $Instance = [PowerShell]::Create()
    $Instance.AddScript($CommandList)
    $Result = $Instance.BeginInvoke()
    $Instance.EndInvoke($Result)

The trouble is output is divided into multiple streams and to report it I must do this:

    $Instance.Streams.Debug
    $Instance.Streams.Error
    $Instance.Streams.Information

This groups messages by type rather than interleaving them so that there is no good way to tell where, within an execution, a given error was thrown. If they were combined, the errors would appear immediately after relevant Write-Host statements.

There appear to be 5 streams(debug, error, information, progress, verbose and warning) and I'd like to combine them all although simply combining error and information would be a huge step forward.

I looked around the $Instance object and tried to find something under InitialSessionState for passing to Create() with nothing obvious presenting itself.

bielawski
  • 1,466
  • 15
  • 20

1 Answers1

5

To access output from all streams in output order when using the PowerShell SDK, you'll have to resort to *>&1 as well:

$Instance = [PowerShell]::Create()

# Example commands that write to streams 1-3.
$CommandList = 'Write-Output 1; Write-Error 2; Write-Warning 3'

# Wrap the commands in a script block (`{...}`) and call it using 
# `&`, the call operator, which allows you to apply redirection `*>&1`
$null = $Instance.AddScript('& {' + $CommandList + '} *>&1')

$Result = $Instance.BeginInvoke()
$Instance.EndInvoke($Result) # Returns output merged across all streams.

Since output objects from streams other than the success stream (1) have a uniform type that reflects the stream of origin, you can examine the type of each output object to infer what stream it came from - see this answer for details.

For more information about PowerShell's 6 output streams, run Get-Help about_Redirection.

mklement0
  • 382,024
  • 64
  • 607
  • 775