考虑脚本“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 的输出?
最佳答案
我看了一些关于 powershell 流水线的文章。所使用的 cmdlet 返回一组对象,以及 powershell 的 default behavior是将输出转发到屏幕。
This article解释了 break 语句将中断管道(实际上,它会中断执行,直到找到父循环),从而解释了第一个示例的行为。
至于第二个例子,我假设 powershell 只会在脚本执行结束时默认重定向到控制台。由于 $host.ui.PromptForChoice 不使用第一个 cmdlet 调用的输出,而是自己生成,因此只会丢弃 Get-EventLog 的结果。
就目前而言,正如@Christian 所说,始终使用“Out-Host”是 the way to go .
关于Powershell cmdlet 输出未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14326490/