質問

今日、私は困惑している興味深い問題に遭遇しました。冗長ストリームから出力をキャプチャし、標準出力に書き込む必要があります。

これは次のようにして実現できます。

# 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帰属
所属していません StackOverflow
scroll top