петлю трубы для просмотра сетки и очистки сетки на каждом цикле?

Мне просто интересно, могу ли я очистить Out-Gridview в каждом цикле, как в консоли:

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

К сожалению, это не очищает сетку каждый раз:

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

1 ответ

Clear-Host clears the display of the host, which is the console window's content in a regular PowerShell console.

By contrast, Out-GridView is a separate GUI window, over which PowerShell offers no programmatic display once it is being displayed.
Notably, you can neither clear no refresh the window's content after it is displayed with the initial data.

The best approximation of this functionality is to close the old window and open a new one with the new data in every iteration - but note that this will be visually disruptive.

In the simplest case, move the Out-GridView into the loop and call it with -Wait, which requires you to close it manually in every iteration, however:

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

This answer shows how to implement an auto-closing Out-GridView window, but it is a nontrivial effort - and with a sleep period as short as 1 second it will be too visually disruptive.

Ultimately, what you're looking for is a GUI version of the Unix watch utility (or, more task-specifically, the top utility).

However, since you're not looking to interact with the Out-GridView window, there's little benefit to using Out-GridView in this case.

Instead, you could just spawn a new console window that uses Clear-Host to display the output in the same screen position periodically:

The following defines helper function Watch-Output to facilitate that:

# 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командлет, который не только предотвращает мерцание, но и предлагает дополнительные функции. Большой нюанс в том, что - в версии
1.3.6 - в модуле есть несколько командлетов, конфликтующих со встроенными (Format-Hex, Get-Clipboard, New-SelfSignedCertificate, Send-MailMessage,Set-Clipboard), и единственный способ импортировать модуль - разрешить командам модуля переопределять встроенные (Import-Module PowerShellCookbook -AllowClobber).

Другие вопросы по тегам