I use PowerShell a lot while I am in windows. I use a project called ActivityWatch
to monitor my activity on my computers (in the hope that I would reflect on myself). To that extent, I wanted the PowerShell window title to display what I run. It was never a simple thing. And the online search was unhelpful too. I could see how to change any shell type (like bash, fish, zsh, etc.), but not PowerShell. All I knew was to modify a variable $host.UI.RawUI.WindowTitle
.
PreCmd in the form of PSReadLine
PSReadLine module provides a better line editing experience for the PowerShell console. Like the up-arrow which could be configured to search history and so on. I wanted the window title to change when I execute a command. So, I upgraded the default enter functionality by changing the title.
The default function consisted of just accepting the given line.
Set-PSReadLineKeyHandler -Key Enter -Description 'set window title to the current command' -Function AcceptLine
I replaced the function in the above command with a script block as follows:
Set-PSReadLineKeyHandler -Key Enter -Description 'set window title to the current command' -ScriptBlock { # Add to AcceptLine default function
$title = $null;
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$title,[ref]$null)
if($title){$host.UI.RawUI.WindowTitle=$title}
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
GetBufferState will get the line from the command line. We get the command as a title and enter it to the $host.UI.RawUI.WindowTitle
. Finally, run the function that was supposed to run anyway.
Result
When no command is being run, window title is the default one.
When a command is entered, it is reflected on the title.