Clear-Host Deconstructed

Sometimes, just sitting inside my console, I issue a few consecutive commands, and suddenly, I have something worth sharing. Recently, as I prepared to work with something other than PowerShell, I cleared the host. It's a common occurrence -- probably for us both, even. After doing so, I decided to take a closer look at the command I had just issued.

PS > Get-Command -Name cls

CommandType     Name                  Version    Source
-----------     ----                  -------    ------
Alias           cls -> Clear-Host

PS > Get-Command -Name Clear-Host

CommandType     Name                  Version    Source
-----------     ----                  -------    ------
Function        Clear-Host

In the first above command, we ran Get-Command against "cls" and determined that it's an alias for Clear-Host. In the second command, we followed up by determining that Clear-Host is a function. For me, the absolute first thing I do when I realize a command is a function, and not a cmdlet, is peer into the code that makes it do, what it does.

In the below example, we return the ScriptBlock property of our Clear-Host function. While you can instead return the Definition property, I've always just used ScriptBlock. It makes more sense to me and is easier to remember. But in my experience, functions have the same code twice, in two different properties.

PS > (Get-Command -Name Clear-Host).ScriptBlock

$RawUI = $Host.UI.RawUI
$RawUI.CursorPosition = @{X=0;Y=0}
$RawUI.SetBufferContents(
    @{Top = -1; Bottom = -1; Right = -1; Left = -1},
    @{Character = ' '; ForegroundColor = $rawui.ForegroundColor; BackgroundColor = $rawui.BackgroundColor})
# .Link
# https://go.microsoft.com/fwlink/?LinkID=225747
# .ExternalHelp System.Management.Automation.dll-help.xml

The Clear-Host function includes a few things I decided to go over myself, and then share here, as well. We essentially have three commands inside this function. The very first command sets the variable $RawUI to the values stored in the host's RawUI property. The host in discussion here refers to the host program that's hosting the PowerShell engine and has nothing to do with a computer host.

After the $RawUI variable is created and populated, we then alter the location of the cursor within the host program. It's moved from its current location in the host program, wherever that might be, to the topmost and leftmost position within the host. While it'll be for a millisecond or two, do keep in mind that it will eventually be forced into its final position by the execution of the prompt function, moving it to the right as is necessary. Even so, this movement won't happen until after the Clear-Host script block is complete, and there's still a final command to execute.

The third and final command to execute when the Clear-Host function is invoked, uses the SetBufferContents method. This method requires two arguments. The first argument is the Rectangle. As Clear-Host uses -1 for the Top, Bottom, Right, and Left, the entire screen of the host program will be filled in. Think of the console screen -- this host program -- as the rectangle. And yes, you read that correctly. We're going to fill in our host program's screen.

The second argument, which is also an array such as the first argument was, includes three keys, not four as we just saw. The first is Character. This indicates what single character should be used to fill in the screen. Clear-Host uses an empty space, such as ' '. As  you start testing (or planning pranks, duh), be sure to change this to other single characters, such I did to create the below image.

Finally, the last two keys in the hash table that make up this second argument, allow us to choose the foreground and background colors to be used inside the host. The default that my Windows PowerShell host wants to use is black, over the Windows PowerShell standard blue, so this needs to be included.

And that's it. After the variable assignment, the Clear-Host function essentially has two commands. To review, it positions the cursor at the top-left corner of the host, fills in the screen with an empty space at every position inside the host program, and sets the foreground and background color to what it already was.

Before we wrap it up here, I had an idea (that I would never really implement). Instead of using the default colors used by Clear-Host, you can create your own Clear-Host function that uses random colors for the foreground and background colors. I won't bother providing a demonstration, but take the below code and supplant it into the above code and enjoy!

ForegroundColor = ([System.Enum]::GetNames([System.ConsoleColor]) | Get-Random); BackgroundColor = ([System.Enum]
::GetNames([System.ConsoleColor]) | Get-Random)})

Update 2/5/2019: After a few days' time, I decided I should include an gif of what happens when we alter the Clear-Host function with the above Get-Random commands. So, here's that:

≥ Tommy Maynard (Twitter: @thetommymaynard)

About Tommy Maynard

IT Pro. Passionate for #PowerShell, #AWS (certified x2), & all things automation. I'm not done learning. Author in #PSConfBook. Writes at https://powershell.org.

2 thoughts on “Clear-Host Deconstructed

  1. JJJessee

    Looks good.
    A help request.
    I'm fumbling with
    $Host.PrivateData.ErrorForegroundColor = [System.Windows.Media.Color]'#FF00F200'
    it works in ISE
    But would like to set custom #hex colors in the vsCode terminal with System.ConsoleColor
    PS 5.1
    any suggestions?

    JJJ

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort