Adding Live Clock to PowerShell Title Bar (Part 2)

by Jul 25, 2017

In the previous tip we presented code that would update the PowerShell title bar in a background thread, displaying a live clock.

Wouldn’t it be nice to also show the current path location? The challenge: how would the background thread know the current path of the foreground PowerShell?

There is a PowerShell variable called $ExecutionContext which provides all kinds of useful information on the state of a context, including the current path. By passing the $ExecutionContext from the foreground process to your background thread, the thread can display the current path of the foreground process.

Try it:

$code = 
{
    # submit the host process RawUI interface and the execution context
    param($RawUi, $ExecContext)

    do
    {
        # find the current location in the host process
        $location = $ExecContext.SessionState.Path.CurrentLocation
        # compose the time and date display
        $time = Get-Date -Format 'HH:mm:ss dddd MMMM d'
        # compose the title bar text
        $title = "$location     $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).AddArgument($ExecutionContext)
$handle = $ps.BeginInvoke()

When you run this code, the PowerShell title bar shows the current path and the live clock. When you switch the current path, i.e. by running “cd c:\windows”, the title bar immediately updates.

There are plenty of use cases here that can be tackled with the code above:

  • You could show notification messages when lunch time approaches
  • You could end your PowerShell session after a given time
  • You could display RSS feed items in your title bar

Twitter This Tip! ReTweet this Tip!