Customizing the PowerShell command prompt

By default, the PowerShell command prompt does not echo the current working directory. To customize the command prompt, simply create a function named prompt. If you want this customization to persist, add it to your profile.

For example, adding the following line to your profile will cause the working directory to be displayed much like it is in cmd.exe.

function prompt { "$pwd>" }

However, the prompt function can contain any code at all. Here’s a prompt function that will display the right-most part of the working directory. This keeps long working directory names from taking up most of the space at the command line.

function prompt
    $m = 30 # maximum prompt length
    $str = $pwd.Path
    if ($str.length -ge $m)
        # The prompt will begin with "...",
        # end with ">", and in between contain
        # as many of the path characters as will fit,
        # reading from the end of the path.
        $str = "..." + $str.substring($str.length - $m + 4)
    "$str> "

For example, if

C:Documents and SettingsAdministratorMy DocumentsMy Music

is the current directory, the prompt would be

...atorMy DocumentsMy Music>

Update: See the next post for an update.

Tagged with:
Posted in PowerShell
One comment on “Customizing the PowerShell command prompt
  1. Alf says:

    my way to do it


    function prompt
    $cwd = (get-location).Path

    do {$cwdi=$cwd.indexofany(“\”,$cwdi+1) ; [array]$cwdt+=$cwdi} until($cwdi -eq -1)

    if ($cwdt.count -gt 3) {
    $cwd = $cwd.substring(0,$cwdt[0]) + “..” + $cwd.substring($cwdt[$cwdt.count-3])

    $host.UI.RawUI.WindowTitle = “$(hostname) – $env:USERDNSDOMAIN$($env:username)”
    $host.UI.Write(“Yellow”, $host.UI.RawUI.BackGroundColor, “[PS]“)
    ” $cwd>”

3 Pings/Trackbacks for "Customizing the PowerShell command prompt"
  1. [...] John Cook has a new blog post that talks about customizing the PowerShell command prompt [...]

  2. [...] to define a function called "prompt" that returns a String. I found a nice prompt script there, but was not satisfied with it as it hides the drive. I modified it a bit in order to show the [...]

  3. [...] The Endeavor – Customizing the PowerShell command prompt [...]