How can I use tilde in the powershell prompt? How can I use tilde in the powershell prompt? powershell powershell

How can I use tilde in the powershell prompt?


You can replace $HOME with ~ using normal string replacement. Ex.

Get the current prompt-function:

Get-Content Function:\prompt    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";    # .Link    # http://go.microsoft.com/fwlink/?LinkID=225750    # .ExternalHelp System.Management.Automation.dll-help.xml

Then replace $home with ~ when the current path is $home or $home\*.

Using switch (readable):

function global:prompt {    $path = switch -Wildcard ($executionContext.SessionState.Path.CurrentLocation.Path) {        "$HOME" { "~" }        "$HOME\*" { $executionContext.SessionState.Path.CurrentLocation.Path.Replace($HOME, "~") }        default { $executionContext.SessionState.Path.CurrentLocation.Path }    }    "PS $path$('>' * ($nestedPromptLevel + 1)) ";}

Using regex (recommended):

function global:prompt {    $regex = [regex]::Escape($HOME) + "(\\.*)*$"    "PS $($executionContext.SessionState.Path.CurrentLocation.Path -replace $regex, '~$1')$('>' * ($nestedPromptLevel + 1)) ";}

Using Split-Path (ugly):

function global:prompt {    $path = $executionContext.SessionState.Path.CurrentLocation.Path    $p = $path    while ($p -ne "") {        if($p -eq $HOME) { $path = $path.Replace($HOME,"~"); break}        $p = Split-Path $p    }    "PS $path$('>' * ($nestedPromptLevel + 1)) ";}

Demo:

PS C:\> cd ~PS ~> cd .\DesktopPS ~\Desktop>