Adding Live Clock to PowerShell Title Bar (Part 1)

by Jul 24, 2017

To continuously update the PowerShell title bar, and for example display the current date and time, you need a background thread that takes care of this. Without a background thread, your PowerShell would be busy all the time updating the title bar, thus unusable.

Here is a simple piece of code you can run to display a live clock in your title bar:

$code = 
    # submit the host process RawUI interface and the execution context

        # compose the time and date display
        $time = Get-Date -Format 'HH:mm:ss dddd MMMM d'
        # compose the title bar text
        $title = "Current Time: $time" 
        # output the information to the title bar of the host process
        $RawUI.WindowTitle = $title
        # wait a half second
        Start-Sleep -Milliseconds 500
    } while ($true)
$ps = [PowerShell]::Create()
$null = $ps.AddScript($code).AddArgument($host.UI.RawUI)
$handle = $ps.BeginInvoke()

The crucial thing here is to pass over the $host.UI.RawUI object from your foreground PowerShell to your background thread code. Only then can your background thread access the title bar owned by your foreground PowerShell.

Twitter This Tip! ReTweet this Tip!