PowerShell命令输出未显示

5

考虑脚本“test.ps1”:

Get-EventLog -list | gm

当从Powershell控制台调用(“.\test.ps1”)时,它会按预期输出成员。

然而,以下脚本没有显示“Get-EventLog -list | gm”的输出:

脚本1

Get-EventLog -list | gm
break

脚本 2

Get-EventLog -list | gm

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Continua execucao"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Cancela operacao"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice("Title", "Message", $options, 0) 

如果我把“Get-EventLog -list | gm”改成像“Hello World”这样的文本,它会正确地显示,两种情况都是如此。为什么cmdlet的输出没有显示?

3
一个解决方法是强制将输出发送到主机:Get-EventLog -list | gm | out-host - CB.
1个回答

3

我看了一些关于powershell流水线的文章。使用的cmdlet返回对象集合,powershell的默认行为是将输出转发到屏幕上。

这篇文章解释了break语句会中断管道(实际上,它会中断执行直到找到父循环),从而解释了第一个例子的行为。

至于第二个例子,我认为powershell只会在脚本执行结束时默认重定向到控制台。由于$host.ui.PromptForChoice不使用第一个cmdlet调用的输出,并且生成自己的输出,因此来自Get-EventLog的结果被丢弃。

目前来看,始终使用"Out-Host",如@Christian所说,是正确的方法


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接