Ausführliche Ausgabe von erfassen -Ausführlicher Schalter in PowerShell v2
-
21-12-2019 - |
Frage
Ich bin heute auf ein interessantes Thema gestoßen, das mich verwirrt hat.Ich muss die Ausgabe aus dem ausführlichen Stream erfassen und in stdout schreiben.
Dies kann damit erreicht werden:
# 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
Der interessante Teil ist nun, wenn ich eine Funktion namens erstellen würde Hello-World
und verwenden [CmdletBinding()]
um den Schalter -verbose zu erben, kann ich die Ausgabe nicht mehr erfassen:
Function Hello-World {
[CmdletBinding()]
Param()
Write-Verbose "hello world"
}
...
$null = $psCmd.AddScript({Hello-World -Verbose }).Invoke()
...
Ich gehe davon aus, dass die Funktion einen eigenen ausführlichen Stream erhält und die Sichtbarkeit des Streams verloren geht, aber ich bin nicht positiv.Hat das damit zu tun [CmdletBinding()]
?
Transkripte vermeiden, gibt es eine Möglichkeit, dies zu erreichen?
Danke!
Lösung
Danke @JasonMorgan, unten ist die Lösung, die zu funktionieren scheint.Ich musste die Funktion in der von mir erstellten pscmd deklarieren:
$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