My PowerShell Prompt

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: ,

5 Comments

  1. Hal Rottenberg

    And if you want more than one letter of the parent folders in the prompt, Tomas gave this to me to use:
    return ($loc -replace ‘\\(\.?)([^\\]{3})[^\\]*(?=\\)’,’\$1$2′)
    This replaces the similar line in the shorten-path function.

  2. Alex Espinoza

    Very nice. Thank you. I just recently found your site… and it rocks!!…. You Color Schemes are very cool. I am recently porting my Web Highlighter profile to your color scheme. And after that, I will add it to my emacs script.

  3. Shay Levy

    To get your computer name try the $env:COMPUTERNAME enevironment variable, it is much more fatser to get and less expnensive than [net.dns]::GetHostName().

  4. Pingback: Episode 110 – Andrew Mason From Microsoft on Server Core « PowerScripting Podcast

  5. Pingback: PowerShell Magazine » Pimp Your Profile

  6. Pingback: Create a PowerShell Visual Studio prompt | Peters's PowerShell Blog

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>