我只是想知道是否可以像在控制台中一样清除每个循环上的 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
我只是想知道是否可以像在控制台中一样清除每个循环上的 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
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-GridView
Out-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-Command
cmdlet,不仅可以避免闪烁,还可以提供其他功能。
最大的警告是 - 从版本1.3.6
开始 - 该模块有几个与内置命令(Format-Hex
, Get-Clipboard
, New-SelfSignedCertificate
, Send-MailMessage
, Set-Clipboard
)冲突的 cmdlet,导入模块的唯一方法是允许模块的命令覆盖内置命令( Import-Module PowerShellCookbook -AllowClobber
)。