我正在处理一个小表格,但我有些困惑。我有一个闭幕事件
$Form.Add_Closing({})
在那里,我想停止自定义日志记录模块,但它不会将输出反射(reflect)到控制台,如果我使用 write-output
。如果我使用 Write-Host ,则会反射(reflect)到控制台。 Closing
事件是否有真正的输出能力?
$Form.Add_Closing({
# my logging function - doesn't work
Write-Log -Stop
# Write-Output - doesn't work
Write-Output 'Test message'
# Write-Host - does work
Write-Host 'Another Test message'
})
最佳答案
该问题适用于所有事件,而不仅仅是关闭
:
PowerShell 内部 script block充当 .NET 事件委托(delegate):
您可以调用任意命令...
...但是他们的成功流(管道)输出被丢弃。
但是,输出到 PowerShell 的任何其他 output streams 确实出现在调用者的控制台中,正如您在 Write-Host
中所经历的那样.
因此,如果您只是想将被调用命令的成功输出打印到调用者的显示屏,您可以将它们通过管道传输到 Out-Host
:
$Form.Add_Closing({
Write-Log -Stop | Out-Host
})
注意:
Out-Host
的输出 - 与Write-Host
不同 - 基本上既不能被捕获也不能被抑制。来自
Write-Host
的输出,由于 v5 通过信息流写入,可以使用6>$null
进行抑制,并且原则上 通过 common-InformationVariable
parameter 捕获,如果您的脚本是 advanced脚本,并使用./yourScript -InformationVariable captureInfoStream
调用它。
但是,这不适用于在事件委托(delegate)脚本 block 内进行的Write-Host
调用。
如果您想要收集从事件委托(delegate)脚本 block 发出的成功输出,以便稍后在脚本中使用(这也允许您控制是否将收集的输出发送到脚本的调用者),在脚本范围中创建一个列表,您可以从事件委托(delegate)脚本 block 附加到该列表:
# Initialize a list to collect event-delegate output in.
$outputFromEventDelegates = [Collections.Generic.List[object]] @()
# ...
$Form.Add_Closing({
# Call the function of interest and add its output to the
# script-scope list.
$outputFromEventDelegates.AddRange(
@(Write-Log -Stop)
)
})
# ... after the .ShowDialog() call
# Now you can access all collected output.
Write-Verbose -Verbose "Output collected from event delegates:"
$outputFromEventDelegates
关于forms - PowerShell 表单。如果我无法调用函数或使用 Write-output,但在我的 Form Closing 事件中,如果我使用 Write-Host,它会起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74703992/