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?

2014-07-09 11_53_20-

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:

2014-07-09 11_57_40-posh~git ~ powershell_scripts [master] (Admin)

For this and other powershell scripts check out my github.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>