从PowerShell v2中的-Verbose开关捕获详细输出

时间:2014-07-30 17:33:52

标签: powershell output powershell-v2.0 cmdlet

今天我遇到一个有趣的问题让我感到困惑。我需要从详细流中捕获输出并将其写入stdout。

这可以通过以下方式实现:

# 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

现在有趣的部分是,如果我要创建一个名为Hello-World的函数并使用[CmdletBinding()]继承-verbose开关,我将无法再捕获输出:

Function Hello-World {
    [CmdletBinding()]
    Param()

    Write-Verbose "hello world"
}

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

我假设函数有自己的详细流,并且流的可见性丢失,但我不是正面的。这是否与[CmdletBinding()]有关?

避免成绩单,有没有办法实现这个目标?

谢谢!

1 个答案:

答案 0 :(得分:2)

谢谢@JasonMorgan,下面是解决方案似乎正在运作。我需要在pscmd中声明函数:

$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