Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the PowerShell prompt to show just the parent directory and current directory?

I would like to shorten my PowerShell prompt so that it just shows the parent directory and the current directory. For example, if the pwd is

C:\Users\ndunn\OneDrive\Documents\Webucator\ClassFiles\python-basics\Demos

I want the prompt to be:

PS ..\python-basics\Demos> 

I can get it to be just PS ..\Demos> by changing the prompt() function in the Profile file:

  1. Find location of Profile file by running $profile in PowerShell.
  2. Open (or create and open) Profile file.
  3. Change (or add) the following prompt() function:

function prompt
{
  $folder = "$( ( get-item $pwd ).Name )"
  "PS ..\$folder> "
}

I tried using split() and negative indexing, but wasn't able to get it to work.

Also, I only want to do this if the pwd is at least two levels down. If the pwd is something like C:\folder\folder, I'd like to show the default prompt.

Any ideas?

like image 653
Webucator Avatar asked Dec 31 '22 13:12

Webucator


2 Answers

Try the following function, which should work on Windows and Unix-like platforms (in PowerShell Core) alike:

function global:prompt {
  $dirSep = [IO.Path]::DirectorySeparatorChar
  $pathComponents = $PWD.Path.Split($dirSep)
  $displayPath = if ($pathComponents.Count -le 3) {
    $PWD.Path
  } else {
    '…{0}{1}' -f $dirSep, ($pathComponents[-2,-1] -join $dirSep)
  }
  "PS {0}$('>' * ($nestedPromptLevel + 1)) " -f $displayPath
}

Note that I've chosen single character (HORIZONTAL ELLIPSIS, U+2026) to represent the omitted part of the path, because .. could be confused with referring to the parent directory.

Note: The non-ASCII-range character is only properly recognized if the enclosing script file - assumed to be your $PROFILE file - is either saved as UTF-8 with BOM[1] or as UTF-16LE ("Unicode").

If, for some reason, that doesn't work for you, use three distinct periods ('...' instead of '…'), though note that that will result in a longer prompt.


[1] The BOM is only a necessity in Windows PowerShell; by contrast, PowerShell Core assumes UTF-8 by default, so no BOM is needed.

like image 158
mklement0 Avatar answered Apr 28 '23 22:04

mklement0


These other replies were much more involved. Even so, here's mine. If it's greater than 30 characters, we shorten the path. Done.

Function Prompt {
    If ("$($executionContext.SessionState.Path.CurrentLocation)>".Length -le 30) {
        "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
    } Else {
        "PS ...\$(Split-Path -Path $executionContext.SessionState.Path.CurrentLocation -Leaf)$('>' * ($nestedPromptLevel + 1)) ";
    } # End If.
} # End Function: Prompt.

enter image description here

like image 27
tommymaynard Avatar answered Apr 28 '23 22:04

tommymaynard