How to add a machine name color to a PowerShell Remoting session prompt?

To make it more obvious when I retired to the live / production server, I thought it would be convenient to have the color name of the machine I'm connecting to when using remote PowerShell sessions.

However, I see no way to do this ... The server name prefix does not seem to depend on the Prompt function, and even if I could use it, I'm not sure how I could define a new Request only for the duration of the session.

Is there any way to configure this? Note. I do not want all server names to be the same, I would like to distinguish between local / production servers.

+8
powershell powershell-remoting
source share
1 answer

After some searching around, it seems like you're right that there is no built-in hook to redefine the [computername]: tag [computername]: with a preview.

Fortunately, I have a hacking solution that might work for you!

To get the color, we can just use Write-Host . Write-Host output from the prompt function will be completely left, and that is what we want. Unfortunately, the [computername]: tag [computername]: is inserted by default immediately after that. This leads to the fact that the computer name is duplicated in the invitation, once with color and once without it.

We get around this by returning a string containing backspace characters, so non-color [computername]: will be overwritten. This is a normal query string, usually the current path.

Finally, in the case of a short line of the query string and does not completely overwrite the non-color [computername]: tag [computername]: we need to do some final cleanup by adding space characters. However, this may push the caret, so we need to add extra back spaces to get the caret back to the corrent position.

All use this on your remote computer:

 # 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}" } 
+5
source share

All Articles