Neil Houghton asked a couple of days ago if I could share my PowerShell prompt() function. Here's what my prompt looks like:

ps-prompt

I tried to keep my prompt relatively short while still on a single line. There are two things I care about in my prompt: The machine name I'm working on (useful when I have VMs opened) and the current path, in abbreviated form.

Thus, my prompt() function looks like this:

function prompt {
   # our theme
   $cdelim = [ConsoleColor]::DarkCyan
   $chost = [ConsoleColor]::Green
   $cloc = [ConsoleColor]::Cyan

   write-host "$([char]0x0A7) " -n -f $cloc
   write-host ([net.dns]::GetHostName()) -n -f $chost
   write-host ' {' -n -f $cdelim
   write-host (shorten-path (pwd).Path) -n -f $cloc
   write-host '}' -n -f $cdelim
   return ' '
}

The abbreviation of the current directory is partially inspired by Unix (use ~ if it's under the $HOME) and partially by how GVim shortens paths for its tab captions:

vim-tabs

Here's the function that takes care of this:

function shorten-path([string] $path) {
   $loc = $path.Replace($HOME, '~')
   # remove prefix for UNC paths
   $loc = $loc -replace '^[^:]+::', ''
   # make path shorter like tabs in Vim,
   # handle paths starting with \\ and . correctly
   return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2')
}

One thing to keep in mind regarding shorten-path: I do a very simple replace of $HOME by ~. The reason it works correctly is that I ensure in my profile script that the $HOME variable has a fully qualified path and "completed" using the resolve-path command. I also modify what the home directory is under PowerShell by using a trick I've described previously.

Technorati tags: ,


Tomas Restrepo

Software developer located in Colombia.