Powershell cmdlet 输出未显示

Art*_*nes 5 powershell

考虑脚本“test.ps1:

Get-EventLog -list | gm
Run Code Online (Sandbox Code Playgroud)

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

但是,以下脚本不显示“Get-EventLog -list | gm”的输出:

脚本1

Get-EventLog -list | gm
break
Run Code Online (Sandbox Code Playgroud)

脚本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) 
Run Code Online (Sandbox Code Playgroud)

如果我将“Get-EventLog -list | gm”更改为“Hello World”等文本,则在两种情况下都会正确显示。

为什么不显示 cmdlet 的输出?

Art*_*nes 3

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

本文解释了break语句将中断管道(事实上,它将中断执行直到找到父循环),从而解释了第一个示例的行为。

至于第二个示例,我假设 powershell 仅默认在脚本执行结束时重定向到控制台。由于 $host.ui.PromptForChoice 不使用第一个 cmdlet 调用的输出,而是生成它自己的输出,因此 Get-EventLog 的结果将被丢弃。

就目前情况而言,正如 @Christian 所说,始终使用“Out-Host”是正确的方法