Short and sweet powershell prompt with posh-git
My company has fully switched to git and it’s been great. Most people at work use SourceTree as a gui to manage their git workflow, some use only command line, and I use a mixture of posh-git in powershell with tortoise git when I need to visualize things.
Posh-git, if you load the example from your profile, will set the default prompt to be the current path. If you go into a git directory it’ll also add the git status. Awesome. But if you are frequently in directories that are 10+ levels deep, suddenly your prompt is just obscenely long.
For example, this is pretty useless right?
Obviously it’s a fictitious path, but sometimes you run into them, and it’d be nice to optionally shorten that up.
It’s easy to define a shortPwd function and expose a global “MAX_PATH” variable that can be reset.
$MAX\_PATH = 5
function ShortPwd
{
$finalPath = $pwd
$paths = $finalPath.Path.Split('\')
if($paths.Length -gt $MAX\_PATH){
$start = $paths.Length - $MAX\_PATH
$finalPath = ".."
for($i = $start; $i -le $paths.Length; $i++){
$finalPath = $finalPath + "\" + $paths[$i]
}
}
return $finalPath
}
In the posh-git example, make sure to load your custom function first, then change
Write-Host($pwd.ProviderPath) -nonewline
To
Write-Host (ShortPwd) -nonewline -foregroundcolor green
(I like my prompt green)
Now you can dynamically toggle the max length. I’ve set it to 5, but if you change it the prompt will immediately update:
For this and other powershell scripts check out my github.