Adding Clock to PowerShell Console

by May 25, 2012

Maybe you'd like to include dynamic information such as the current time into the title bar of your PowerShell console. You could update the console title bar inside your prompt function, but then the title bar would only get updated each time you press ENTER. Also, the prompt function may be overridden from other code.

A better way is to spawn another PowerShell thread and let it update the title bar text, preserving whatever has been written to the title bar and just adding the information you want, for example the current time (or, for that matter, the current battery load or CPU load, RSS feed or whatever you want to have an eye on).

Here's the code. Be aware that this will only work inside a real PowerShell console, not inside the ISE editor. After you run this code, call Add-Clock to add the current time to your console title bar.

function Add-Clock {
 $code = { 
    $pattern = '\d{2}:\d{2}:\d{2}'
    do {
      $clock = Get-Date -format 'HH:mm:ss'

      $oldtitle = [system.console]::Title
      if ($oldtitle -match $pattern) {
        $newtitle = $oldtitle -replace $pattern, $clock
      } else {
        $newtitle = "$clock $oldtitle"
      }
      [System.Console]::Title = $newtitle
      Start-Sleep -Seconds 1
    } while ($true)
  }

 $ps = [PowerShell]::Create()
 $null = $ps.AddScript($code)
 $ps.BeginInvoke()
}

Twitter This Tip! ReTweet this Tip!