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.

One thought on “Customizing the PowerShell command prompt

  1. my way to do it

    thanks

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

    [array]$cwdt=$()
    $cwdi=-1
    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>”
    }

Comments are closed.