从 PowerShell v2 中的 -Verbose 开关捕获详细输出
-
21-12-2019 - |
题
今天遇到一个有趣的问题,让我很困惑。我需要捕获详细流的输出并将其写入标准输出。
这可以通过以下方式完成:
# 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
不隶属于 StackOverflow