Совершено недавно открыл для себя эту оболочку. Тут же полез искать книги, которые, кстати, уже перевели и их можно взять отсюда. И все вроде бы хорошо, и код пишется легко и интеграция с vsb-скиптами, но, почему то, тянет меня к мастдайным окнам.
И так, было решено перекрасить окошко PowerShell в стандартный цвет cmd и параллельно настроить автозапуск собственных функций и алиасов. Так же, слегка, напрягало предложения ввода с надписью — PS, которое, совместно с цветом, напоминает лого Adobe Photoshop ( Ничего против Adobe не имею ).
Итак, информация следом исключительно для новичков.
Первым делом запускаем оболочку, видим привычное окно:
Во-первых, нам понадобятся права на запуск отдельных скриптов с расширением ps1.
Посмотреть их можно выполнив команду:
Get-ExecutionPolicy
По умолчанию идет политика: Restricted, которая запрещает выполнение любых скриптов.
Тут три варианта.
1. Либо изменить политику на AllSigned и подписывать скрипты ( подробнее можете прочитать выполнив команду get-help about_signing ).
2. Либо именить политику на RemoteSigned, разрещающая запускать все скрипты, за исключением скаченных из сети.
3. Или изменить политику на Unrestricted, позволяющая выполнять любые скрипты, за исключением скаченных, на на выполнение которых будет выдаваться запрос.
Я выбрал второй путь, он, все же, безопасней. Поэтому меняем политику командой:
Set-ExecutionPolicy RemoteSigned
Получаем запрос на изменение политики на который нужно ответить Y(да).
Во-вторых, создадим скрипт, который будет запускаться вместе с PowerShell:
New-Item -type file $PROFILE
По идее, на данном моменте может выскочить вот такая ошибка:
Но ничего страшного, оболочка пишет что не существует папки WindowsPowerShell в Моих Документах, создадим её и повторим команду:
Как мы видим, создался пустой файл с названием Microsoft.PowerShell_profile.ps1.
Половину работы мы сделали. У нас есть права на выполнение скриптов и создан скрипт, подгружающийся по умолчанию.
В-третьих, нам нужно научиться получать и изменять информацию об оболочке.
Командлет Get-Host как раз таки этим и занимается:
Свойство UI на самом деле является объектом, и если мы введем (Get-Host).UI, то увидим, что у этого объекта так же есть свойство RawUI, которое как раз и содержит нужные нам настройки:
(Get-Host).UI.RawUI
Изменять эти настройки можно так:
(Get-Host).UI.RawUI.WindowTitle = “Окно”
(Get-Host).UI.RawUI.BackgroundColor = “Black”
cls
Важно, для того чтобы измененые настройки сразу отображались на экране, нам необходимо прописать алиес cls отвечающий за очистку экрана.
Это, конечно же все круто, но настройки сбрасываются если закрыть окно, поэтому запишем их в файл, который загружается с оболочкой на старте. Редактируем файл Microsoft.PowerShell_profile.ps1 примерно так:
# We to Hell?! - Is't WorldCount!
# Изменяем настройки окна
(Get-Host).UI.RawUI.ForegroundColor="Gray";
(Get-Host).UI.RawUI.backgroundColor="Black";
(Get-Host).UI.RawUI.CursorSize=10;
(Get-Host).UI.RawUI.WindowTitle="WorldCount Console";
# Очищаем экран
cls
# Выводим приветствие
echo " ";
echo "Привет, WorldCount!";
echo " ";
echo " ";
# Устанавливаем начальный каталог
$MyRoot = "C:\Shell\";
CD $MyRoot;
# Вид предложения ввода
function prompt
{
"[WorldCount:] " + $(get-location) + "> "
}
А теперь коротко по коду.
Первые 4-ре свойства отвечают за настройку окна, после установки свойств делаем обязательное очищение — cls.
Cd $MyRoot; — отвечает за то, в каком каталоге при загрузке оболочки мы окажемся.
Функция promt — стандартная видоизмененная функция, которая отвечает за вид строки ввода. Я убрал PS и добавил свой ник.
Сохраняем файл, перезапускаем оболочку.
Выглядит это вот так:
Ну и на последок, в файл Microsoft.PowerShell_profile.ps1 вы можете легко написать свои алиесы. Допустим
set-alias WeToFuck Get-Process
Всем спасибо, удачи в освоении этой прекрасной оболочки.
To change the PowerShell console text color, you can use the `Write-Host` cmdlet with the `-ForegroundColor` parameter, as illustrated in the following code snippet:
Write-Host 'Hello, World!' -ForegroundColor Green
Understanding PowerShell Colors
What are PowerShell Colors?
PowerShell colors serve a functional purpose beyond aesthetics. These colors are crucial in distinguishing between different types of output, including:
- Errors: Typically represented in red, allowing users to quickly identify issues in their scripts.
- Success Messages: Often shown in green, indicating successful execution.
- Warnings: Usually displayed in yellow, alerting users to potential concerns that require attention.
Understanding these color cues can significantly improve your efficiency when using PowerShell, as they allow you to visually parse information quickly.
Default Color Settings
By default, PowerShell comes with a preset color scheme that many users find sufficient. However, the default colors may not be optimal for everyone’s visual preferences or working environment. For instance, the standard black background with white text can be hard on the eyes during long coding sessions. Customizing your PowerShell color scheme can enhance readability and minimize eye strain.
Exchange PowerShell Commands Made Easy
Changing Console Colors Using the Properties Window
An intuitive way to change PowerShell color is through the Console Properties Window. Here’s how you can do it:
- Launch PowerShell and right-click the title bar.
- Select Properties from the context menu.
- Navigate to the Colors tab.
- Here, you can adjust the Screen Text and Screen Background colors using the provided options.
Each color represents specific attributes (for instance, the color white usually indicates standard output). By experimenting with different combinations, you can create a console that suits your needs.
Using PowerShell Commands to Change Colors
In addition to using the GUI, you can also change PowerShell colors programmatically. The `Set-ItemProperty` cmdlet is particularly useful for this purpose.
Change Background and Foreground Colors
Here’s an example of how to change the background and foreground colors using PowerShell commands:
Set-ItemProperty -Path 'HKCU:\Console' -Name 'ScreenColors' -Value 0x0F
In this command:
- `0x0F` indicates the combination of background and foreground colors as per the console’s color palette. The first digit represents the background, while the second digit represents the text.
You can find a complete list of color codes in the PowerShell documentation or by experimenting with your settings.
Changing Color Scheme Permanently
If you want your color settings to persist across PowerShell sessions, you can modify your PowerShell profile. This method ensures that your preferred colors are applied each time you launch PowerShell.
To edit your profile, you can use the following code snippet:
if ($host.Name -eq 'ConsoleHost') {
$host.ui.RawUI.BackgroundColor = 'Black'
$host.ui.RawUI.ForegroundColor = 'Green'
Clear-Host
}
In this example:
- The background color is set to black, and the foreground color is set to green. The `Clear-Host` command refreshes the console to apply the new settings immediately.
Change PowerShell Directory: A Simple Step-by-Step Guide
Advanced Customization Techniques
Creating Custom Color Schemes
Creating a custom color scheme can greatly enhance the usability of your PowerShell interface. A popular choice among software developers might be a dark background with contrasting colors for output like:
- Light Gray for Information
- Yellow for Warnings
- Cyan for File Paths
- White for Standard Output
You can configure these settings using the commands discussed earlier. Making your console more visually appealing and functional not only helps with productivity but also makes coding enjoyable.
Saving and Sharing Custom Color Settings
PowerShell allows you to export your color settings easily, making it simple to share your personalized setup with others or to back it up. Use the following command to export your settings:
Export-Clixml -InputObject $Host.UI.RawUI -Path "C:\path\to\your\colorSettings.xml"
This command saves your current console UI settings, including colors, to an XML file. You can later import these settings on another machine using the `Import-Clixml` cmdlet.
PowerShell Colors: Adding Vibrance to Your Scripts
Troubleshooting Common Issues
Colors Not Applying After Change
If you find that the colors are not changing as expected, there could be several reasons:
- Session Type: Make sure you are in a standard console host; some integrated environments may not reflect custom settings immediately.
- Admin Permissions: Some changes may require administrator privileges to apply.
Check these factors to ensure that your adjustments take effect.
Reverting to Default Colors
If you want to revert your PowerShell colors back to the default settings, use the following command:
Set-ItemProperty -Path 'HKCU:\Console' -Name 'ScreenColors' -Value 0x07
This will reset your color settings to the original color scheme, which is generally a white background with black text.
Understanding Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Conclusion
Changing PowerShell color is not just about beautification; it significantly increases the usability and functionality of your PowerShell workspace. The ability to customize your console enhances your coding experience, allowing for quicker identification of issues and easier readability of scripts. Don’t hesitate to experiment with different schemes and make the interface uniquely yours.
Mastering Microsoft.PowerShell.Commands.WriteErrorException
Call to Action
If you found this guide helpful, consider subscribing for more tips and techniques on mastering PowerShell. Join our community and enhance your scripting skills with our comprehensive courses designed for every level!
Handy PowerShell Scripts for Everyday Tasks
Additional Resources
For more information on configuring your PowerShell environment, refer to the official PowerShell documentation, which offers detailed insights into various command usage and customization techniques. You can also explore third-party tools that allow for advanced console customization options, enriching your experience even further.
-
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"
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:
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
-
makc3000 😊excited
- IT
- Cancel
В данной статье хочу поговорить об изменении вида консоли PowerShell.
Что мы будем с ней делать:
1. Изменение цвета шрифта и фона.
2. Изменение размера окна
3. Изменение заголовка окна
Изменение цвета шрифта и фона.
За цвет фона отвечает переменная $Host.UI.RawUI.BackgroundColo
- Black (черный)
- DarkBlue (темно-синий)
- DarkGreen (темно-зеленый)
- DarkCyan (темно-лазурный)
- DarkRed (темно-красный)
- DarkMagenta (темно-пурпурный)
- DarkYellow (темно-желтый)
- Gray (серый)
- DarkGray (темно-серый)
- Blue (синий)
- Green (зеленый)
- Cyan (лазурный)
- Red (красный)
- Magenta (пурпурный)
- Yellow (желтый)
- White (белый)
Цвет шрифта меняется переменной $Host.UI.RawUI.ForegroundColo
Таким образом, задав переменные
$Host.UI.RawUI.BackgroundColor = «Gray»
$Host.UI.RawUI.ForegroundColor = «DarkGreen»
можно получить следующую картину:
Для того, чтобы настройки цвета сохранились при следующем запуске консоли, необходимо сохранить их в профиле.
Для начала выясним где хранится профиль:
$profile
Теперь создайте текстовый файл с перечисленными выше переменными и сохраните их по пути, указанном в $profile
В следующий раз для изменения профиля можно использовать команду, которая открывает с помощью блокнота ваш профиль:
notepad $profile
The first ever Windows PowerShell was released over a decade ago for Windows XP, Windows Server 2003 and Windows Vista. It’s been a constant part of all Windows editions since then, starting with Windows 7 in 2009. While there have been many changes made to the software itself, the one thing that has stayed unchanged over the years is the color scheme – a blue background with white/yellow text in general, and red text on a black background for error messages. While most people have gotten used to these colors, some of you may want something more distinctive, either for better visibility or for aesthetic reasons. That being the case, let’s talk a look at how you can change Windows PowerShell color scheme in Windows 10:
Note: Before we proceed, it’s important to understand that this particular tutorial will deal with the PowerShell console, and not the PowerShell ISE, which is one of the two host applications for Windows PowerShell engine and language. It has it’s own customization settings that need to be tackled separately, and is beyond the scope of this tutorial.
Change Background and Foreground Colors in Windows 10 PowerShell Console
- As mentioned earlier, Windows PowerShell console displays white on blue by default and red on black for error messages, so to change colors, right-click on the PowerShell Window top-bar, and select ‘Properties’.
- Once the Windows PowerShell ‘Properties’ box pops up, click on the ‘Colors’ tab, and you’ll get a whole host of choices to set background and foreground colors as seen in the screenshot below.
From here, you can change text colors, popup text colors, background colors and even set the opacity levels.
Change Error Message Colors in Windows 10 PowerShell Console
- While this was a really easy way to change some of the settings, what if you want to do more extensive changes to your PowerShell console? For example, what if you want to change the text and background colors of error messages from red on black to something a little less drastic? For that, you’ll need to get down and dirty and use the console itself rather than rely on GUI. First off, to know the default colors, go ahead and copy/paste this code on the PowerShell console and press ‘Enter’:
$host.privatedata
- To change the foreground and background colors of error messages, all you need to do is assign new values. Since I’d like to change the background color to ‘Magenta’ and foreground color to ‘Green’, I’ll input the two commands below. Just remember to enter them separately and press ‘Enter’ in each case.
$host.PrivateData.ErrorBackgroundColor = "Magenta"
$host.PrivateData.ErrorForegroundColor = "Green"
- You have now configured your console settings, but you’ll need to save them to your profile settings so that the screen opens up exactly as you want it to, every time. For that, first run the command
$profile
. This will show you the name (and location) of the default file for your profile.
- In reality, though, the default PowerShell configuration file does not even exist in most cases. So run the following command to check if it already exists or if you need to create it from scratch:
test-path $profile
. If the file already exists, you’ll get a “True” output, else, you’ll get “False”.
- As you can see from the above screenshot, I got the latter, so I’ll need to create the file. If you get “True”, skip this step and go to the next. Else, enter the following command to create the file:
New-Item -path $profile -type file -force
- Once the file is created, you can easily edit it with Notepad by using the
notepad $profile
command in the Powershell Window. From there, you can add whatever configuration code you want to using the commands discussed above. You can not only change colors, but also fonts, windows size, etc through this method, but we’re only going to take a look at changing colors without complicating matters any further.
$console = $host.ui.rawui
$console.backgroundcolor = "black"
$console.foregroundcolor = "white"
$colors = $host.privatedata
$colors.verbosebackgroundcolor = "Magenta"
$colors.verboseforegroundcolor = "Green"
$colors.warningbackgroundcolor = "Red"
$colors.warningforegroundcolor = "white"
$colors.ErrorBackgroundColor = "DarkCyan"
$colors.ErrorForegroundColor = "Yellow"
set-location C:\
clear-host
- We’re almost there, but there’s one last step. Run the following command to permit local scripts to run on your system:
Set-ExecutionPolicy RemoteSigned
and select “A” to allow all scripts. Now that you’re done, this is how your PowerShell console would look every time you start it up. Even the errors messages would look a little less jarring than they normally do.
That’s it, folks, I’ve made the Windows PowerShell console on my work laptop look almost exactly like the good old Command Prompt with just a dash of color thrown in for fun.
Note: While the aforementioned steps are meant specifically for Windows 10, I also tried them out on our older Dell desktop running Windows 7. Every step is pretty much identical, and every thing worked as expected.
SEE ALSO: How to Stop Windows 10 Updates From Installing Automatically
Use Simple Commands To Change Windows PowerShell Colors in Windows 10
The Windows PowerShell is a great tool for power users but that doesn’t mean it has to be dull, drab and boring. Tweaking a few setting here and there can make a world of difference to how your PowerShell console looks, so give it a go and change the colors to whatever your heart feels like. And once you do that, don’t forget to give us a heads-up about how things went, because we love hearing from you.