Clearing Console Content

by Oct 21, 2010

When you want to clear the console content, you probably use "cls" or Clear-Host. For some strange reason, the Clear-Host cmdlet really is a function and uses a lot of internal code. Essentially, it clears every single buffer cell one by one causing flickering, especially with large console buffers.

get-command clear-host | Select-Object -expand Definition
$space = New-Object System.Management.Automation.Host.BufferCell
$space.Character = ' '
$space.ForegroundColor = $host.ui.rawui.ForegroundColor
$space.BackgroundColor = $host.ui.rawui.BackgroundColor
$rect = New-Object System.Management.Automation.Host.Rectangle
$rect.Top = $rect.Bottom = $rect.Right = $rect.Left = 1
$origin = New-Object System.Management.Automation.Host.Coordinates
$Host.UI.RawUI.CursorPosition = $origin
$Host.UI.RawUI.SetBufferContents($rect, $space)

A much faster and easier way is calling Clear(). You could then overwrite the Clear-Host function to take advantage of that:

Function Clear-Host { [System.Console]::Clear() }

This really is a lot faster and prevents some occasional flickering.

Twitter This Tip!
ReTweet this Tip!