Catturazione dell'uscita verbose da -verbose interruttore in PowerShell V2
-
21-12-2019 - |
Domanda
Sono stato in un problema interessante oggi che mi ha perplesso perplesso.Ho bisogno di catturare l'uscita dal flusso verboso e scriverlo su stdout.
Questo può essere realizzato con questo:
# 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
.
Ora la parte interessante è se dovessi creare una funzione chiamata Hello-World
e utilizzare [CmdletBinding()]
per ereditare l'interruttore -verbose, non posso più acquisire l'uscita:
Function Hello-World {
[CmdletBinding()]
Param()
Write-Verbose "hello world"
}
...
$null = $psCmd.AddScript({Hello-World -Verbose }).Invoke()
...
.
Assumendo che la funzione venga dato il proprio flusso verboso e quella visibilità al flusso è persa, ma non sono positivo.Questo ha a che fare con [CmdletBinding()]
?
Evitare le trascrizioni, c'è un modo per realizzare questo?
Grazie!
Soluzione
Grazie @JasonMorgan, sotto è la soluzione che sembra funzionare.Avevo bisogno di dichiarare la funzione nel PSCMD che ho fatto:
$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
.