簡體   English   中英

如何在PowerShell Remoting會話的提示符下為計算機名稱添加顏色?

[英]How can I add color to the machine name in the prompt of a PowerShell Remoting session?

為了使當我遠程連接到實時/生產服務器時更加明顯,我認為使用遠程PowerShell會話時能夠為我連接的計算機名稱着色會很方便。

但是,我看不到這樣做的方法...服務器名稱前綴似乎與Prompt函數無關,即使我可以使用它,也不確定如何僅針對以下內容定義新的Prompt會話的持續時間。

有沒有一種方法可以自定義? 注意:我不想為所有服務器名稱都塗上相同的顏色,我想區分本地服務器/生產服務器。

經過一番搜索之后,似乎沒有使用內置的鈎子來覆蓋預提示[computername]:標簽是正確的。

幸運的是,我有一個不錯的解決方法,可以為您服務!

為了獲得顏色,我們可以只使用Write-Host prompt功能的Write-Host輸出將完全左對齊,這就是我們想要的。 不幸的是,默認的[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}"
}

我使用Posh-Git完成此操作。 請參閱其提示自定義 我注意到某些文檔有些過時,如果您僅在PowerShell中鍵入$GitPromptSettings ,您將看到所有可用屬性。 使用Posh-Git具有在提示上查看Git統計信息的額外好處。

我用來設置機器名稱的命令是...

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

這是顏色設置

$ GitPromptSettings.DefaultPromptPath.ForegroundColor ='橙色'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM