【问题标题】:Powershell cmdlet output not shownPowershell cmdlet 输出未显示
【发布时间】:2020-01-23 14:33:32
【问题描述】:

考虑脚本“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 的输出?

【问题讨论】:

  • 一种解决方法是强制输出到主机:Get-EventLog -list | gm | out-host

标签: powershell


【解决方案1】:

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

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

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

就目前而言,始终使用“Out-Host”,正如@Christian 所说,是the way to go

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多