Link to home
Start Free TrialLog in
Avatar of ugeb
ugebFlag for United States of America

asked on

Customize powershell window title

I have having my PowerShell prompt be the really long directory name it sometimes is, so I put it in my title.  In my profile.ps1 file I have the following lines to set my window title to my current path:

$NewTitle="Dir: " + (get-location).toString()
$host.ui.rawui.set_WindowTitle($NewTitle)

Open in new window


This code has two problems.  The first is that it only seems to work on startup of a shell and isn't refreshed with each command or change of directory.  The second problem is that even this can be too long to fit in my title.  How can I add a function to my ps1 file to change my window title as follows:

1) If the whole directory path fits in the window title, use it
2) If the path doesn't fit, make the window title the following:
   a) First 3 directories, e.g. "C:\Users\Derek" + ...
   b) The remainder of the title to be the path that fits in the title, starting from the end.
     
If, for example, my path is
"c:/Users/Derek/Documents/WindowsPowerShell/Modules/Open-Xml-PowerTools-vNext/OpenXmlPowerToolsExamples/"

This is about 102 characters and let's say the title can only be 75 (I don't know the real #).
With these, I would want my window title to be :
"c:/Users/Gene/Documents.../Modules/Open-Xml-PowerTools-vNext/OpenXmlPowerToolsExamples/"

How can this be done in PowerShell (auto change title & new title text)?
Thanks!
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

wrap it in a function called 'prompt'
function prompt {
$NewTitle="Dir: " + (get-location).toString()
$host.ui.rawui.set_WindowTitle($NewTitle)
}

Open in new window

Done!
Avatar of ugeb

ASKER

This doesn't address the real question of how to have the shortened text. How do I do that?
ASKER CERTIFIED SOLUTION
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ugeb

ASKER

That works great, thank you!  (Worked perfectly once I found the small typo in split using "/" instead of "\").
Thanks again!