I ran into an interesting issue today that has me puzzled. I need to capture output from the verbose stream and write it to stdout.
This can be accomplished with this:
# 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
$psCmd.Commands.Clear()
# Now that I've cleared the pipeline, I'll add another script that writes out 100 messages to the Verbose stream
$null = $psCmd.AddScript({Write-verbose "hello World" }).Invoke()
# Finally, I'll output the stream
$psCmd.Streams.Verbose
Now the interesting part is if I were to create a function called Hello-World and use [CmdletBinding()] to inherit the -verbose switch, I can no longer capture output:
Function Hello-World {
[CmdletBinding()]
Param()
Write-Verbose "hello world"
}
...
$null = $psCmd.AddScript({Hello-World -Verbose }).Invoke()
...
I am assuming that the function is given its own verbose stream and that visibility to the stream is lost, but I am not positive. Does this have to do with [CmdletBinding()]?
Avoiding transcripts, is there a way to accomplish this?
Thanks!
$pscmdlet.WriteVerbose("Hello World")