Windows PowerShell:更改命令提示符

q5lcpyga  于 2023-05-19  发布在  Windows
关注(0)|答案(8)|浏览(430)

使用Windows PowerShell,如何更改命令提示符?
例如,默认提示符为

PS C:\Documents and Settings\govendes\My Documents>

我想定制那个字符串。

5cnsuln7

5cnsuln71#

只需将函数prompt放入您的PowerShell配置文件(notepad $PROFILE)中,例如:

function prompt {"PS: $(get-date)>"}

或彩色:

function prompt
{
    Write-Host ("PS " + $(get-date) +">") -nonewline -foregroundcolor White
    return " "
}
vxbzzdmp

vxbzzdmp2#

与Ocaso Protal的回答相关的评论,Windows Server 2012以及Windows 7(在PowerShell窗口中)需要以下内容:

new-item -itemtype file -path $profile -force
notepad $PROFILE

如果你使用多个用户名(例如:您自己+生产登录):

function Global:prompt {"PS [$Env:username]$PWD`n>"}

(图为大卫I。麦金托什为这一个。)

ux6nzvsh

ux6nzvsh3#

在提示符下,我喜欢当前时间戳和网络驱动器的已解析驱动器号。为了使它更具可读性,我把它放在两行,并发挥了一点与颜色。
有了CMD,我最终得到了

PROMPT=$E[33m$D$T$H$H$H$S$E[37m$M$_$E[1m$P$G

对于PowerShell,我得到了相同的结果:

function prompt {
    $dateTime = get-date -Format "dd.MM.yyyy HH:mm:ss"
    $currentDirectory = $(Get-Location)
    $UncRoot = $currentDirectory.Drive.DisplayRoot

    write-host "$dateTime" -NoNewline -ForegroundColor White
    write-host " $UncRoot" -ForegroundColor Gray
    # Convert-Path needed for pure UNC-locations
    write-host "PS $(Convert-Path $currentDirectory)>" -NoNewline -ForegroundColor Yellow
    return " "
}

更有可读性一点:-)
顺便说一句:

  • 我更喜欢powershell_ise.exe $PROFILE而不是(dumb)Notepad
  • 如果你想用断点调试prompt(),你应该将prompt-function重命名为其他任何东西(或者在另一个文件中尝试)。否则,你可能会陷入一个循环:停止调试时,将再次调用prompt(),并再次在断点处停止。一开始很烦人...
3wabscal

3wabscal4#

如果你想自己做,那么Ocaso Protal's answer就是你要走的路。但如果你像我一样懒惰,只是想找点东西帮你做,那么我强烈推荐Luke Sampson's Pshazz package
为了向您展示您有多懒,我将提供一个快速教程。

  • 使用Scoopscoop install pshazz)安装Pshazz
  • 使用漂亮的预定义主题(pshazz use msys
  • 喝(根汁)啤酒

Pshazz还允许您创建自己的主题,这就像配置JSON文件一样简单。Check out mine来看看有多容易!

lzfw57am

lzfw57am5#

仅显示我使用的驱动器号:

function prompt {(get-location).drive.name+"\...>"}

然后回到我使用的路径:

function prompt {"$pwd>"}
yqkkidmi

yqkkidmi6#

如果您Set-Location到网络共享,此版本的Warren Stevens' answer避免了路径中嘈杂的“Microsoft.PowerShell.Core\FileSystem”。

function prompt {"PS [$Env:username@$Env:computername]$($PWD.ProviderPath)`n> "}
zzwlnbp8

zzwlnbp87#

PowerShell中的PROMPT

一个更好的跟踪路径的方法,同时在每一行运行中保留主机名和日志记录时间/日期:

function prompt {
    $dateTime = get-date -Format "dd.MM.yyyy HH:mm:ss"
    $currentDirectory = $(Get-Location)
    $UncRoot = $currentDirectory.Drive.DisplayRoot
    write-host "$dateTime" -NoNewline -ForegroundColor YELLOW
    write-host " $UncRoot" -ForegroundColor White
    # Convert-Path needed for pure UNC-locations
    write-host "$ENV:COMPUTERNAME-PS:$(Convert-Path $currentDirectory)>" -NoNewline -ForegroundColor GREEN
    return " "
}

...然后你会得到:

myservername-C:\Users\myusername\Documents\WindowsPowerShell\scripts>

最后!:)

z0qdvdin

z0qdvdin8#

PowerShell提示

如果有人正在寻找一个更复杂的答案,这里是我在一年中开发的PowerShell v7提示符。把它放在上下文中,它是我个人PowerShell配置文件的一部分:
https://github.com/StefanGreve/profile

免责声明

启动并运行一个花哨的PowerShell提示符的最简单方法是使用pwsh社区创建的已建立的解决方案,所以如果你只需要在你的终端上编写几行代码,你可能想看看这个项目:
https://github.com/dahlbyk/posh-git
但是,如果您像我一样,想从头开始编写自己的自定义提示符,那么下面的代码片段可能能够为您提供一些关于如何解决这个问题的想法。

自定义提示

我将在这里分解最重要的部分。首先,我添加了必要的代码来确定我们所处的当前平台(因为有些位是特定于操作系统的,我也在基于Unix的操作系统上使用此函数):

enum OS
{
    Unknown = 0
    Windows = 1
    Linux = 2
    MacOS = 3
}

# I map these booleans to an Enum so that I can switch over them
$global:OperatingSystem = if ([OperatingSystem]::IsWindows()) {
    [OS]::Windows
} elseif ([OperatingSystem]::IsLinux()) {
    [OS]::Linux
} elseif ([OperatingSystem]::IsMacOS()) {
    [OS]::MacOS
} else {
    [OS]::Unknown
}

# In the prompt function below this is used to toggle the leading char ('>' or '#') to indicate elevated privilages
if ([OperatingSystem]::IsWindows()) {
    $global:IsAdmin = ([Principal.WindowsPrincipal][Principal.WindowsIdentity]::GetCurrent()).IsInRole([Principal.WindowsBuiltInRole]::Administrator)
}

if ([OperatingSystem]::IsLinux()) {
    $global:IsAdmin = $(id -u) -eq 0
}
# Required for Python if you want to set the venv indicator in the terminal yourself, else skip this part
$env:VIRTUAL_ENV_DISABLE_PROMPT = 1
# Returns the execution time of the last command you ran, or 0 on init
function Get-ExecutionTime {
    $History = Get-History
    $ExecTime = $History ? ($History[-1].EndExecutionTime - $History[-1].StartExecutionTime) : (New-TimeSpan)
    Write-Output $ExecTime
}

构建完成后,我们可以继续深入实际的prompt函数:

function prompt {
    $ExecTime = Get-ExecutionTime

    # Only show the current branch if we are inside a Git repository. Notice that the Git command writes to stderr if we are not inside a Git repository
    $Branch = if ($(git rev-parse --is-inside-work-tree 2>&1) -eq $true) {
          # If you version of git doesn't support the --show-current flag yet, use this command instead:
          # git rev-parse --abbrev-ref HEAD
          # It's less readable so I opted for the more modern approach but you may want to use the command above if using the latest versions of programs isn't your thing
          [string]::Format(" {0}({1}){2}", $PSStyle.Foreground.Blue, $(git branch --show-current), $PSStyle.Foreground.White)
    }

    # You can delete this part if you don't use Python, it is used to indicate whether a virtual environment is active
    $Venv = if ($env:VIRTUAL_ENV) {
        [string]::Format(" {0}({1}){2}", $PSStyle.Foreground.Magenta, [Path]::GetFileName($env:VIRTUAL_ENV), $PSStyle.Foreground.White)
    }

    $Computer = switch ($global:OperatingSystem) {
        ([OS]::Windows) {
            [PSCustomObject]@{
                UserName = $env:USERNAME
                HostName = $env:COMPUTERNAME
            }
        }
        ([OS]::Linux) {
            [PSCustomObject]@{
                UserName = $env:USER
                HostName = hostname
            }
        }
        ([OS]::MacOS) {
            # I don't have a Mac so I cannot guarantee that this bit works, but in theory it should do the trick based on what I found online
            [PSCustomObject]@{
                UserName = id -un
                HostName = scutil --get ComputerName
            }
        }
    }

    return [System.Collections.ArrayList]@(
        "[",
        $PSStyle.Foreground.BrightCyan,
        $Computer.UserName,
        $PSStyle.Foreground.White,
        "@",
        $Computer.HostName,
        " ",
        $PSStyle.Foreground.Green,
        [DirectoryInfo]::new($ExecutionContext.SessionState.Path.CurrentLocation).BaseName,
        $PSStyle.Foreground.White,
        "]",
        " ",
        $PSStyle.Foreground.Yellow,
        "(",
        $ExecTime.Hours.ToString("D2"),
        ":",
        $ExecTime.Minutes.ToString("D2"),
        ":",
        $ExecTime.Seconds.ToString("D2"),
        ":",
        $ExecTime.Milliseconds.ToString("D3"),
        ")",
        $PSStyle.Foreground.White,
        $Branch,
        $Venv, # (you may want to remove this line, see remark above)
        "`n",
        [string]::new($global:IsAdmin ? "#" : ">", $NestedPromptLevel + 1),
        " "
    ) -join ""
}

相关问题