Clear-Host Deconstructed


Notice: The following post was originally published on another website. As the post is no longer accessible, it is being republished here on tommymaynard.com. The post was originally published on January 31, 2019.


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

Edit: The link in the above code no longer works. It just ends up at Bing. The current link, when viewing this ScriptBlock now, is https://go.microsoft.com/fwlink/?LinkID=2096480. Other than that, it does not appear anything else has changed since 2019 when this post was originally published.

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 the discussion here refers to the host program that’s hosting the PowerShell engine and has nothing to do with a computer host. These settings include things like the ForegroudColor and BackgroundColor, the WindowSize, WindowsTitle, and more. The Idea, however, is that only the Foreground and Background color will be used in the third command discussed below.

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 (0,0). 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 a hash table 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.

Note: The originally published image was unrecoverable.

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)})

Leave a Reply

Your email address will not be published. Required fields are marked *