如何在Powershell提示中使用波浪号? [英] How can I use tilde in the powershell prompt?

查看:260
本文介绍了如何在Powershell提示中使用波浪号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我明白了:

function global:prompt {
    # Commands go here
}

在powershell中设置提示。我可以使用 Get-Location 来获取当前的工作目录。而且我可以 cd〜并放在我的主目录中。

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.

但是我可以让提示使用波浪号吗?例如,如果我在 / home / mike 中,它应该只显示

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

我尝试过以下测试:

$pwd -contains $home

但是结果不正确。

如何在Powershell的提示符中使用〜?

推荐答案

您可以替换 $ HOME 使用常规字符串替换。例如。

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

获取当前的提示功能:

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

然后将 $ home 替换为,当当前路径为 $ home $ home\ * 时。

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

使用开关(可读):

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)) ";

}

使用分割路径(丑陋):

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:

Demo:

PS C:\> cd ~

PS ~> cd .\Desktop

PS ~\Desktop>

这篇关于如何在Powershell提示中使用波浪号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆