Created
November 19, 2012 15:33
-
-
Save anonymous/4111290 to your computer and use it in GitHub Desktop.
Powershell Watch-Command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
## Author : Roman Kuzmin | |
## Synopsis : Watch one screen of commands output repeatedly | |
## Modified : 2006.11.06 | |
## Source : http://nightroman.wordpress.com/2006/09/26/watch-command-ps1-watch-commands-output-repeatedly/?replytocom=43#respond | |
## | |
## Modified : 2012.11.15 - tgmayfield - Support for System.Double wait times, output a title string similar to *nix watch command | |
## | |
## -Command_: script block which output is being watched | |
## -Seconds : refresh rate in seconds | |
## | |
## *) Commands should not operate on console. | |
## *) Tabs are simply replaced with spaces. | |
## *) * indicates truncated lines. | |
## *) Empty lines are removed. | |
## *) Ctrl-C to stop. | |
## | |
function Watch-Command | |
{ | |
param([scriptblock]$Command_ = {Get-Process}, [double]$Seconds = 2) | |
$private:ms = [int]($Seconds * 1000) | |
$private:sb = New-Object System.Text.StringBuilder | |
$private:w0 = $private:h0 = 0 | |
for(;;) { | |
# invoke command, format output data | |
$private:n = $sb.Length = 0 | |
$private:w = $Host.UI.RawUI.BufferSize.Width | |
$private:h = $Host.UI.RawUI.WindowSize.Height-1 | |
$private:title = [System.String]::Format("Every {0:N1}s: {1}", $Seconds, $Command_) | |
[void]$sb.EnsureCapacity($w*$h) | |
.{ | |
$private:dateDisplay = [System.DateTime]::Now.ToString("G") | |
[void]$sb.Append($title) | |
[void]$sb.Append(" ($dateDisplay)") | |
[void]$sb.AppendLine() | |
[void]$sb.AppendLine() | |
++$n | |
++$n | |
& $Command_ | Out-String -Stream | .{process{ | |
if ($_ -and ++$n -le $h) { | |
$_ = $_.Replace("`t", ' ') | |
if ($_.Length -gt $w) { | |
[void]$sb.Append($_.Substring(0, $w-1) + '*') | |
} | |
else { | |
[void]$sb.Append($_.PadRight($w)) | |
} | |
} | |
}} | |
}>$null | |
# fill screen | |
if ($w0 -ne $w -or $h0 -ne $h) { | |
$w0 = $w; $h0 = $h | |
Clear-Host; $private:origin = $Host.UI.RawUI.CursorPosition | |
} | |
else { | |
$Host.UI.RawUI.CursorPosition = $origin | |
} | |
Write-Host $sb -NoNewLine | |
$private:cursor = $Host.UI.RawUI.CursorPosition | |
if ($n -lt $h) { | |
Write-Host (' '*($w*($h-$n)+1)) -NoNewLine | |
} | |
elseif($n -gt $h) { | |
Write-Host '*' -NoNewLine | |
} | |
$Host.UI.RawUI.CursorPosition = $cursor | |
Start-Sleep -Milliseconds $ms | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment