Windows – How to change the PowerShell title when the working directory changes

command linepowershellwindows

While working in long path sub directories, the prompt is 90% of the window width.
I can change the prompt with this:

# Save to: %userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
function prompt
{
    Write-Host ("PS>") -nonewline -foregroundcolor Green -backgroundcolor Black
    return " "
}

But, what I want is to change the title of the window as I change directories.

Is there an event I can hook so that when I type cd c:\temp that the title becomes c:\temp, and my PS prompt remains PS>?

Best Answer

The Prompt function is called every time a new prompt is printed. Its return value is the string PowerShell will display as the prompt, but you can do other things in it as well. If you save this as your profile, you'll get what you want:

Function Prompt {
    $host.UI.RawUI.WindowTitle = Get-Location
    "PS> "
}

(Source: this Microsoft blog article.) It sets the window title to the current location, then returns the constant string PS> .

Related Question