Truncated output when running Powershell command in a loop

I wrote the following function as a rudimentary way of implementing basic functionality of the *nix watch command within Powershell:

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

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

When working with cmdlets that return Powershell objects, I get strange behavior. For example if I run `watch 'get-command ls', on the first iteration I get the following formatted output of the object:

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

But on the second and subsequent iterations, it truncates the object property headers (and any description above it in certain other commands):

Alias           ls -> Get-ChildItem

I'm curious as to why this behavior happens, and how I can make the output identical to the first iteration for all subsequent iterations. I am running this in Powershell 5.1 on Windows 10.


I think it's because you're mashing up Write-Output which writes to the pipeline, and clear which is properly named Clear-Host and clears the local terminal, and knows nothing of the pipeline. It goes better with Write-Host .

Since your function loops eternally, the pipeline output never finishes, so what you would get get is this endless list with one set of headings:

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

but you clear the /display/ in the middle of the list, so it carries on printing the subsequent items without the headings.

If you explicitly write to Format-Table in your command you can get the headings repeated:

watch { Get-Alias ls | Format-Table }
链接地址: http://www.djcxy.com/p/30246.html

上一篇: Windows“运行”命令没有找到powershell了

下一篇: 在循环中运行Powershell命令时截断输出