Если при работе в командной строке вы случайно допустите опечатку, скажем, вместо «r» в конце команды dir напечатаете «e», интерпретатор сообщит об ошибке, но ничем иным кроме как текстовым содержимым это сообщение не будет отличаться. Не так бывает в консоли PowerShell. Ошибки в ней подсвечиваются красным цветом на чёрном фоне и всё это на тёмно-синем окружении основного фона консоли.
Не очень приятное сочетание цветов, не правда ли?
Если вы тоже так считаете, почему бы их не изменить, сделать так, чтобы они гармонировали друг с другом? Начнём с того, что в PowerShell, как и в стандартной командной строке, цвет текста и основного фона можно менять. Кликните правой кнопкой мыши по заголовку окна консоли и выберите в меню «Свойства». В открывшемся окошке переключитесь на вкладку «Цвета» и подберите сочетание цветов для фона и текста, которое с вашей точки зрения является наиболее гармоничным.
Только вот текст ошибок по-прежнему будет выводиться красным цветом на том же чёрном фоне. Как изменить его? Очень просто. Используемые в PowerShell цвета хранятся в объекте PrivateData. Чтобы их просмотреть, содержимое этого объекта необходимо записать в переменную, а затем вывести её на экран. Вот так:
$col=(Get-Host).PrivateData
$col
За цвета сообщений об ошибках отвечают параметры ErrorForegroundColor и ErrorBackgroundColor. Как видим, по умолчанию первый имеет значение Red (красный), а второй значение Black (чёрный). Давайте заменим их.
$col.ErrorBackgroundColor = «Yellow»
$col.ErrorForegroundColor = «Blue»
Готово, теперь можете попробовать намерено выполнить какой-нибудь командлет с ошибкой.
Вы увидите, что цвет текста ошибки и окружающий его фон изменились. При желании можете поэкспериментировать и с другими свойствами. Например, WarningForegroundColor и WarningBackgroundColor отвечают за цвета предупреждений, а DebugForegroundColor и DebugBackgroundColor за сведения об отладке.
Да, чтобы не забыть, все доступные цвета выводятся командой [System.Enum]::GetNames([System.ConsoleColor]).
Способ, как видите, рабочий, но при этом следует помнить, что при завершении сессии созданная вами переменная будет удалена, а вместе с нею к значениям по умолчанию будут приведены свойства цветов. Чтобы сохранить настройки, вам нужно будет добавить их в свой пользовательский профиль. А что такое профиль PowerShell и для чего он нужен, мы поговорим в следующий раз.
Загрузка…
- Remove From My Forums
-
Question
-
When running PowerShell in an elevated command prompt, Win 10’s PoSH seems to want to color different words with different colors a la ISE. Anyway, most of the colors are readable, but some are bit too dark to stand out, and nothing in $host.ui.rawui
seems to change them. Can someone point me to where it gets the idea to make some text yellow, green, white, etc?Thanks.
Answers
-
This isn’t the whole answer, but putting these lines into your powershell profile (a file named profile.ps1 which sits in your DocumentsWindowsPowerShell folder (you may have to create that folder) will remove most of the unreadable colors:
Set-PSReadlineOption -TokenKind comment -ForegroundColor white
Set-PSReadlineOption -TokenKind none -ForegroundColor white
Set-PSReadlineOption -TokenKind command -ForegroundColor white
Set-PSReadlineOption -TokenKind parameter -ForegroundColor white
Set-PSReadlineOption -TokenKind variable -ForegroundColor white
Set-PSReadlineOption -TokenKind type -ForegroundColor white
Set-PSReadlineOption -TokenKind number -ForegroundColor white
Set-PSReadlineOption -TokenKind string -ForegroundColor white
Set-PSReadlineOption -TokenKind operator -ForegroundColor white
Set-PSReadlineOption -TokenKind member -ForegroundColor whiteAnd if you have never done it before, you’ll need just once to type this in PowerShell:
Set-ExecutionPolicy RemoteSigned
-
Marked as answer by
Monday, October 12, 2015 7:18 PM
-
Marked as answer by
I’ve added this function to my powershell profile since there is a program that regularly messes up the colors of my shell.
$DefaultForeground = (Get-Host).UI.RawUI.ForegroundColor
$DefaultBackground = (Get-Host).UI.RawUI.BackgroundColor
function SetColors
{
Param
(
[string]$Foreground = "",
[string]$Background = ""
)
$ValidColors = "black","blue","cyan","darkblue" ,"darkcyan","darkgray",
"darkgreen","darkmagenta","darkred","darkyellow","gray","green",
"magenta","red","white","yellow";
$Foreground = $Foreground.ToLower()
$Background = $Background.ToLower()
if ( $Foreground -eq "" )
{
$Foreground = $DefaultForeground
}
if ( $Background -eq "" )
{
$Background = $DefaultBackground
}
if ( $ValidColors -contains $Foreground -and
$ValidColors -contains $Background )
{
$a = (Get-Host).UI.RawUI
$a.ForegroundColor = $Foreground
$a.BackgroundColor = $Background
}
else
{
write-host "Foreground/Background Colors must be one of the following:"
$ValidColors
}
}
set-alias set-colors SetColors
Some notes:
«$DefaultCololrs = (Get-Host).UI.RawUI» creates more of a pointer-type object than an actual copy of the object. This means that if you later set a different variable equal to «(Get-Host).UI.RawUI», and change things, $DefaultColors will also change (which is why I’ve made sure to copy them here as strings).
I tried setting other colors (using hex codes) with very little luck, though I did find Setting Powershell colors with hex values in profile script (I just haven’t tried it yet, since I’m not particularly fond of mucking about in the registry, and the default list of colors seemed rather sufficient).
I also found this document: https://technet.microsoft.com/en-us/library/ff406264.aspx, which I may have to use later to figure out how to modify my «grep» command (currently I have it aliased to select-string)
если вы случайно допустили опечатку при работе в командной строке, скажите вместо “Р» в конце команды реж тип “А ТАКЖЕ», интерпретатор сообщит об ошибке, но это сообщение будет отличаться только текстовым содержанием. В консоли PowerShell этого не происходит. Ошибки в нем выделены красным цветом на черном фоне и все это находится на синей рамке фона основной консоли.
Не очень приятная цветовая гамма, правда?
Если вы тоже так думаете, почему бы не изменить их, заставить гармонировать друг с другом? Для начала в PowerShell, как и в стандартной командной строке, можно изменить цвет текста и основной фон. Щелкните правой кнопкой мыши строку заголовка окна консоли и выберите в меню «Свойства». В открывшемся окне переключитесь на вкладку «Цвета» и выберите цветовую схему для фона и текста, которая, с вашей точки зрения, является наиболее гармоничной.
Только теперь текст ошибки по-прежнему будет отображаться красным цветом на том же черном фоне. Как мне это изменить? Очень простой. Цвета, используемые в PowerShell, хранятся в объекте PrivateData. Для их отображения содержимое этого объекта должно быть записано в переменную и затем отображено на экране. Нравится:
$ col = (Get-Host) .PrivateData
$ col
Параметры ErrorForegroundColor и ErrorBackgroundColor отвечают за цвета сообщений об ошибках. Как видите, по умолчанию первое Красный (Красный), а второе значение Black (Чернить)… Заменим их.
$ col.ErrorBackgroundColor = “Желтый”
$ col.ErrorForegroundColor = “Синий”
Готово, теперь вы можете попробовать намеренно запустить некоторые командлеты с ошибкой.
Вы увидите, что цвет текста ошибки и окружающего фона изменились. Если хотите, можете поэкспериментировать с другими свойствами. Например, WarningForegroundColor и WarningBackgroundColor предназначены для цветов предупреждений, а DebugForegroundColor и DebugBackgroundColor – для отладочной информации.
Да не забыть, все доступные цвета отображаются командой [System.Enum] :: GetNames ([System.ConsoleColor]).
Метод, как видите, работает, но при этом следует помнить, что в конце сеанса созданная вами переменная будет удалена и вместе с ней для свойств цвета будут установлены значения по умолчанию. Чтобы сохранить настройки, вам нужно будет добавить их в свой профиль пользователя. Мы поговорим о том, что такое профиль PowerShell и каким он будет в следующий раз.
Источник изображения: www.white-windows.ru
- Introduction to Changing Colors in PowerShell
- Use the
[System.Enum]
Class in PowerShell - Changing the Console Color in PowerShell
This article will discuss how to change font colors, the background color of scripts, and the console window color using PowerShell.
Introduction to Changing Colors in PowerShell
These commands retrieve an object with information about the PowerShell console, the console host.
Command:
Output:
Name : Windows PowerShell ISE Host
Version : 5.1.22000.282
InstanceId : 8cff2bea-868b-4d9e-b55a-06a3f4b8c20c
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-PH
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.Host.ISE.ISEOptions
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
The PrivateData
property has all the color properties we are looking for.
Command:
Output:
ErrorForegroundColor : #FFFF9494
ErrorBackgroundColor : #00FFFFFF
WarningForegroundColor : #FFFF8C00
WarningBackgroundColor : #00FFFFFF
VerboseForegroundColor : #FF00FFFF
VerboseBackgroundColor : #00FFFFFF
DebugForegroundColor : #FF00FFFF
DebugBackgroundColor : #00FFFFFF
ConsolePaneBackgroundColor : #FF012456
ConsolePaneTextBackgroundColor : #FF012456
ConsolePaneForegroundColor : #FFF5F5F5
ScriptPaneBackgroundColor : #FFFFFFFF
ScriptPaneForegroundColor : #FF000000
The colors are set for the Warnings, Errors, Debug, Verbose, and Progress streams inside the $host.PrivateData
object. Try changing one of these values and seeing if your console also changes colors.
Command:
$host.PrivateData.ErrorBackgroundColor = "White"
The error background default color "black"
will change to "white"
.
To query for all the console colors in PowerShell, we run the command below.
Command:
[System.Enum]::GetValues('ConsoleColor')
Output:
Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White
The displayed output on the console is plain white text (if default colors have not been changed). Do the following command to display the console colors as their respective colors.
Command:
[System.Enum]::GetValues('ConsoleColor') |
ForEach-Object { Write-Host $_ -ForegroundColor $_ }
Output:
Suppose we wanted to see which color combinations would work and suit our preference. In that case, we can use the command below that will output all the possible foreground colors on all possible background colors.
Command:
$colors = [enum]::GetValues([System.ConsoleColor])
Foreach ($bgcolor in $colors){
Foreach ($fgcolor in $colors) {
Write-Host "$fgcolor|" -ForegroundColor $fgcolor -BackgroundColor $bgcolor -NoNewLine
}
Write-Host " on $bgcolor"
}
Output:
Changing the Console Color in PowerShell
Changing the prominent console foreground and the background color is slightly different from our previous object. We may try the snippet below to change the text color and the console window of PowerShell.
Command:
$host.UI.RawUI.ForegroundColor = "DarkGreen"
$host.UI.RawUI.BackgroundColor = "Black"
cls
Output:
I know I can change PowerShell console colors by setting in my profile something like:
$Host.UI.RawUI.BackgroundColor = "White"
Clear-Host
However in the Powershell Console one can go to the Color tab in Properties and modify the RGB values of the standard 16 ANSI colors manually. Is it possible to do set either hex or RGB values of the standard colors from the profile script? For instance setting I would like to have:
$Host.UI.RawUI.BackgroundColor = "#242424" # Gray
Clear-Host
asked Apr 29, 2013 at 13:51
2
The correct way to do this is with the Registry
cd hkcu:/console
$0 = '%systemroot%_system32_windowspowershell_v1.0_powershell.exe'
ni $0 -f
sp $0 ColorTable00 0x00562401
sp $0 ColorTable07 0x00f0edee
With the color being
0x00BBGGRR
mpd
2,1931 gold badge19 silver badges23 bronze badges
answered May 18, 2014 at 0:10
4
You can, but not via the $Host
object. The color table is stored in the registry.
You would use the same names, but the colors would be different. That’s why the default PowerShell console is blue/gray.
whitneyland
10.6k9 gold badges59 silver badges67 bronze badges
answered Apr 29, 2013 at 17:49
BartekBBartekB
8,41431 silver badges33 bronze badges
As far as I know, you can’t. The console API doesn’t support custom color. If you do this:
$x = (Get-Host).UI.RawUI
$x | gm
you’ll see that BackgroundColor is of type System.ConsoleColor.
answered Apr 29, 2013 at 14:14
David BrabantDavid Brabant
40.7k16 gold badges85 silver badges108 bronze badges
For anyone that may be looking to custom color the Powershell ISE here is the format.
#Get the list of colors and hex equivalents
[windows.media.colors] | Get-Member -Static -MemberType property |
ForEach-Object {
$psISE.Options.ConsolePaneTextBackgroundColor = `
([windows.media.colors]::$($_.name)).tostring()
"$($_.name) `t $([windows.media.colors]::$($_.name))"
}
#Example of how to change the console color in the powershell ISE
$psISE.Options.ConsolePaneBackgroundColor = '#FF4169E1' #RoyalBlue
$psISE.Options.ConsolePaneTextBackgroundColor = '#00FFFFFF' #Transparent
Proper credit belongs to «The scripting Guy», sorry I don’t have the link but the code is directly from his website.
not2qubit
13.3k8 gold badges89 silver badges122 bronze badges
answered Mar 9, 2020 at 18:58
2