【问题标题】:Truncated output when running Powershell command in a loop在循环中运行 Powershell 命令时截断输出
【发布时间】:2016-10-21 04:22:02
【问题描述】:

我编写了以下函数作为在 Powershell 中实现 *nix watch 命令的基本功能的基本方法:

function watch {
    Param(
        [Parameter(Mandatory=$true)][string]
        $command,
        [Parameter(Mandatory=$false)][int]
        $n = 2
    )

    while($true) {
        clear
        Write-Output (iex $command)
        sleep $n
    }
}

使用返回 Powershell 对象的 cmdlet 时,我遇到了奇怪的行为。例如,如果我运行 `watch 'get-command ls',在第一次迭代中,我会得到对象的以下格式化输出:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ls -> Get-ChildItem

但在第二次和后续迭代中,它会截断对象属性标题(以及某些其他命令中的任何描述):

Alias           ls -> Get-ChildItem

我很好奇为什么会发生这种行为,以及如何使所有后续迭代的输出与第一次迭代相同。我在 Windows 10 上的 Powershell 5.1 中运行它。

【问题讨论】:

  • 因为 Format-Table 隐含地通过管道输出不知道您清除屏幕,它只是继续打印表格,而不是打印新表格。

标签: windows powershell


【解决方案1】:

我认为这是因为您将写入管道的 Write-Output 和正确命名为 Clear-Host 并清除本地终端的 clear 混合在一起,并且对管道一无所知。 Write-Host 会更好。

由于你的函数永远循环,管道输出永远不会结束,所以你会得到这个带有一组标题的无尽列表:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ls -> Get-ChildItem
Alias           ls -> Get-ChildItem
Alias           ls -> Get-ChildItem
Alias           ls -> Get-ChildItem
Alias           ls -> Get-ChildItem
Alias           ls -> Get-ChildItem

但是你清除了列表中间的/display/,所以它会继续打印没有标题的后续项目。

如果你在命令中明确写信给Format-Table,你可以得到重复的标题:

watch { Get-Alias ls | Format-Table }

【讨论】:

  • 我实际上在没有结合 write-output 和 iex 的情况下得到了相同的行为,我结合了 write-output 认为它可能会解决问题,但仍然得到相同的行为。我会尝试添加格式表
  • 好消息,Format-Table 正是我所需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-11-30
  • 2014-10-27
  • 2013-10-12
  • 2014-03-08
  • 2021-12-09
  • 1970-01-01
  • 2020-04-22
相关资源
最近更新 更多