簡體   English   中英

在PowerShell v2中捕獲-Verbose開關的詳細輸出

[英]Capturing verbose output from -Verbose switch in PowerShell v2

今天我遇到了一個有趣的問題,這使我感到困惑。 我需要從詳細流中捕獲輸出並將其寫入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()]嗎?

避免成績單,有沒有辦法做到這一點?

謝謝!

謝謝@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM