3

我只是想知道是否可以像在控制台中一样清除每个循环上的 Out-Gridview:

while (1) { ps | select -first 5; sleep 1; clear-host }

不幸的是,这并不能每次都清除 out-gridview:

 & { while (1) { ps | select -first 5; sleep 1; clear-host } } | out-gridview
4

1 回答 1

2

Clear-Host清除主机的显示,这是常规 PowerShell 控制台中控制台窗口的内容。

相比之下,Out-GridView它是一个单独的 GUI 窗口,PowerShell 在显示后不提供任何程序化显示。
值得注意的是,在显示初始数据后,您既不能清除也不能刷新窗口的内容。

此功能的最佳近似值是关闭旧窗口并在每次迭代中使用新数据打开一个新窗口 - 但请注意,这将在视觉上造成破坏。

在最简单的情况下,将Out-GridView移入循环并使用 调用它-Wait,这需要您在每次迭代中手动关闭它,但是:

# NOTE: Doesn't move to the next iteration until you manually close the window.
while (1) { ps | select -first 5 | Out-GridView -Wait }

这个答案显示了如何实现自动关闭Out-GridView窗口,但这是一项不平凡的工作 - 睡眠时间短至一1秒钟,它会在视觉上造成太大的破坏。

最终,您正在寻找的是 Unixwatch实用程序的 GUI 版本(或者,更具体地,该top实用程序)。

但是,由于您不希望与窗口进行交互,因此在这种情况下使用 没有什么好处Out-GridViewOut-GridView

相反,您可以只生成一个新的控制台窗口,用于Clear-Host定期在同一屏幕位置显示输出:

以下定义了帮助函数Watch-Output以促进这一点:

# Simple helper function that opens a new console window and runs
# the given command periodically, clearing the screen beforehand every time.
function Watch-Output ([scriptblock] $ScriptBlock, [double] $timeout = 1) {
  $watchCmd = @"
   while (1) { 
     Clear-Host
     & { $($ScriptBlock -replace '"', '\"') } | Out-Host
     Start-Sleep $timeout 
   }
"@                                                                                                            #'
  Start-Process powershell.exe "-command $watchCmd"
}

# Invoke with the command of interest and a timeout.
Watch-Output -ScriptBlock { ps | Select -First 5 } -Timeout 1

请注意,每次刷新窗口内容时,它仍然会闪烁。避免这种情况需要付出更多的努力。

PowerShellCookbook模块提供了复杂的Watch-Commandcmdlet,不仅可以避免闪烁,还可以提供其他功能。
最大的警告是 - 从版本1.3.6开始 - 该模块有几个与内置命令(Format-Hex, Get-Clipboard, New-SelfSignedCertificate, Send-MailMessage, Set-Clipboard)冲突的 cmdlet,导入模块的唯一方法是允许模块的命令覆盖内置命令( Import-Module PowerShellCookbook -AllowClobber)。

于 2019-12-14T13:37:16.273 回答