9

为了让我在远程到实时/生产服务器时更加明显,我认为在使用远程 PowerShell 会话时能够为我连接的机器名称着色会很方便。

但是,我看不到这样做的方法......服务器名称前缀似乎独立于 Prompt 函数,即使我可以使用它,我也不确定如何定义一个新的 Prompt 仅用于会话的持续时间。

有没有办法自定义这个?注意:我不想将所有服务器名称都涂成相同的颜色,我想区分本地/生产服务器。

4

2 回答 2

6

经过一番搜索后,您似乎是正确的,没有内置的钩子可以覆盖预提示[computername]:标记。

幸运的是,我有一个可以为您工作的 hacky 解决方法!

要获得颜色,我们可以使用Write-Host. Write-Host函数的输出prompt将完全左对齐,这是我们想要的。不幸的是,默认[computername]:标签是在之后直接插入的。这导致计算机名称在提示中重复,一次有颜色,一次没有。

我们通过返回一个包含退格字符的字符串来解决这个问题,因此未着色的[computername]:将被覆盖。这是正常的提示字符串,通常是当前路径。

最后,如果正常提示字符串很短并且没有完全覆盖未着色的[computername]:标签,我们需要通过添加虚拟空格字符来进行最后的清理。但是,这可能会推出插入符号,因此我们需要添加更多的退格来将插入符号返回到正确的位置。

总而言之,在您的远程机器上使用它:

# put your logic here for getting prompt color by machine name
function GetMachineColor($computerName)
{
   [ConsoleColor]::Green
}

function GetComputerName
{
  # if you want FQDN
  $ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
  "{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName

  # if you want host name only
  # $env:computername
}

function prompt
{
  $cn = GetComputerName

  # write computer name with color
  Write-Host "[${cn}]: " -Fore (GetMachineColor $cn) -NoNew

  # generate regular prompt you would be showing
  $defaultPrompt = "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "

  # generate backspaces to cover [computername]: pre-prompt printed by powershell
  $backspaces = "`b" * ($cn.Length + 4)

  # compute how much extra, if any, needs to be cleaned up at the end
  $remainingChars = [Math]::Max(($cn.Length + 4) - $defaultPrompt.Length, 0)
  $tail = (" " * $remainingChars) + ("`b" * $remainingChars)

  "${backspaces}${defaultPrompt}${tail}"
}
于 2012-12-03T22:42:30.357 回答
0

我使用Posh-Git来实现这一点。查看他们的提示定制。我注意到有些文档有点过时了,如果你只输入$GitPromptSettingsPowerShell,你会看到所有可用的属性。使用 Posh-Git 的额外好处是可以在提示符上查看 Git 统计信息。

我用来设置机器名的命令是...

$GitPromptSettings.DefaultPromptPrefix = '$(get-content env:computername) '

这里是颜色设置

$GitPromptSettings.DefaultPromptPath.ForegroundColor = '橙色'

于 2018-10-19T22:12:59.063 回答