Dan*_*eny 8 powershell powershell-remoting powershell-3.0
为了让我更加明显,当我远程连接到实时/生产服务器时,我认为在使用远程PowerShell会话时能够为我连接的机器名称着色是很方便的.
但是,我看不到这样做的方法......服务器名称前缀似乎独立于提示功能,即使我可以使用它,我也不确定如何定义新的提示会议的持续时间.
有没有办法定制这个?注意:我不想为所有服务器名称着色相同,我想区分本地/生产服务器.
经过一些搜索之后,似乎你没有内置的钩子来覆盖预提示[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}"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1489 次 |
| 最近记录: |