Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use tilde in the powershell prompt?

So I get that:

function global:prompt {
    # Commands go here
}

Sets the prompt in powershell. I can use Get-Location to get the current working directory. And I can cd ~ and be in my home dir.

But can I make the prompt use the tilde? E.g., if I'm in /home/mike it should just show ~.

I've tried testing with:

$pwd -contains $home

But the results aren't correct.

How can I use ~ in the prompt in powershell?

like image 822
mikemaccana Avatar asked Aug 27 '16 22:08

mikemaccana


People also ask

What does tilde do in PowerShell?

The tilde character ( ~ ) is shorthand notation for the current user's home folder.

How do I use tilde in CMD?

Toggle between open windows of the same app Mac: cmd + ~ (tilde) Alternate between open windows of a single application.

How do you use tabs in PowerShell?

The TAB key has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB , it changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

What is RN in PowerShell?

`r`n is CRLF, the newline sequence composed of a CARRIAGE RETURN ( U+000D ) character immediately followed by an LF, used as a newline on Windows.


1 Answers

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 .\Desktop

PS ~\Desktop>
like image 163
Frode F. Avatar answered Sep 27 '22 02:09

Frode F.