Thursday, November 27, 2014

Capturing Different Types of PowerShell Output

When a PowerShell script runs, it can create a number of different types of output, including success output, errors, warning messages, verbose output, and debug messages. By default, each of these streams of output are merged to the console host when your script runs. This usually makes sense, but some times, you may want to capture the different streams of output separately.

Simon Wahlin has published an interesting article that shows you how you can combine the redirect operator (">") and the stream number to achieve that. This is great information about a somewhat obscure feature. The technique involves combining the re-direct operator with the stream number based on:

Stream Stream Number
All Output *
Success output 1
Error output 2
Warning messages 3
Verbose output 4
Debug output 5

Then you follow the command you want to capture on, the stream number, redirect operator and where you want the output to go. Simon has a simple function that creates each type of output (Write-ToStreams). If you want to capture the output of, say, the verbose stream, you'd run the function like this:

Write-ToStreams 4>4out.txt

And if you wanted to send the verbose output one way, and the error output another, you could achieve it like this:

Write-ToStreams 4>4out.txt 2>2out.txt Tags: ,

No comments: