1

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!

3
  • 1
    Are you sure the function is executing properly? It may be that the function isn't defined in the new powershell instance you're dealing with. Commented Jul 30, 2014 at 17:38
  • Also, within an advanced function ([CmdletBinding()]) you should be using $pscmdlet.WriteVerbose("Hello World") Commented Jul 30, 2014 at 17:42
  • Ahh, that was it, I'll post an update Commented Jul 30, 2014 at 17:43

1 Answer 1

2

Thank you @JasonMorgan, below is the solution that appears to be working. I needed to declare the function in the pscmd I made:

$pscmd = [PowerShell]::Create() 

$null = $psCmd.AddScript({$VerbosePreference = "Continue"},$false).Invoke()
$null = $psCmd.AddScript({
  function Hello-World {
    [CmdletBinding()]
    Param()
    Write-Verbose "hello world"
  }
}, $false).Invoke() 

$psCmd.Commands.Clear() 

$null = $psCmd.AddScript({Hello-World -Verbose }).Invoke() 

$psCmd.Streams.Verbose
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.