Getting Alternate Streams (Verbose, Progress, Debug) with the PowerShell API

Dozens of people could write dozens of books on all of the cool stuff we improved in V2 of PowerShell.  One of the nice little things we did was give a more understandable API than Pipeline (which is the class you can use to invoke code from C# in V1).  This API is called the PowerShell API, and one of the improvements it makes is the ability to get to alternate data streams.

Alternate data streams are a particularly fun thing about PowerShell. While you can have a lot of output streams in DOS, it was anyone’s guess exactly what any of them were.  PowerShell has several alternate data streams that have interesting information.  They are: Verbose, Warning, Debug, Error, and Progress.

Today, Vivek Sharma (a PM in Exchange) wanted to get some samples about how to get at the Verbose Stream in PowerShell.  Here’s an example of how to get at it with the V2 PowerShell API:

# Create a PowerShell Command
$pscmd = [PowerShell]::Create()
# Add a Script to change the verbose preference.
# Since I want to make sure this change stays around after I run the command I set UseLocalScope to $false.
# Also note that since AddScript returns the PowerShell command, I can simply call Invoke on what came back.
# I set the return value to $null to suppress any output
$null = $psCmd.AddScript({$VerbosePreference = "Continue"},$false).Invoke()
# If I added more commands, I’d be adding them to the pipeline, so I want to clear the pipeline
# Now that I’ve cleared the pipeline, I’ll add another script that writes out 100 messages to the Verbose stream
$null = $psCmd.AddScript({1..100 | Foreach-Object { Write-Verbose $_}}).Invoke()
# Finally, I’ll output the stream

Hope this Helps,

James Brundage [MSFT]