A captura de saída detalhada do -parâmetro Verboso no PowerShell v2
-
21-12-2019 - |
Pergunta
Corri para um interessante problema de hoje é que tem me intrigado.Eu precisa para capturar a saída do fluxo detalhado e escrever para stdout.
Isso pode ser feito com este:
# 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
Agora a parte interessante é que se eu fosse criar uma função chamada Hello-World
e usar [CmdletBinding()]
para herdar o parâmetro verboso, não posso capturar a saída:
Function Hello-World {
[CmdletBinding()]
Param()
Write-Verbose "hello world"
}
...
$null = $psCmd.AddScript({Hello-World -Verbose }).Invoke()
...
Eu estou supondo que a função é atribuída a sua própria detalhado fluxo e que a visibilidade para o fluxo está perdido, mas eu não sou positivo.Será que isso tem a ver com [CmdletBinding()]
?
Evitar transcrições, existe uma maneira de fazer isso?
Obrigado!
Solução
Obrigado @JasonMorgan, abaixo está a solução que parece estar a funcionar.Eu precisava declarar a função de pscmd eu fiz:
$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