[computername]:
いくつか検索したところ、pre-promptタグをオーバーライドするための組み込みフックがないことが正しいようです。
幸いなことに、私はあなたのために働くことができるハッキーな回避策を持っています!
色を取得するには、を使用できますWrite-Host
。 Write-Host
関数からの出力はprompt
完全に左寄せされます。これが私たちが望むものです。残念ながら、デフォルトの[computername]:
タグはその直後に挿入されます。その結果、コンピューター名がプロンプトで複製されます。1回は色付き、もう1回は色なしです。
これを回避するには、バックスペース文字を含む文字列を返すため、色の付いていない文字[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}"
}