Powershell: попытка изменить цвета заднего / переднего плана на вывод текста (без Write-Host) - PullRequest
0 голосов
/ 07 мая 2020

Как следует из названия, я пытаюсь изменить цвет переднего края / фона текста, выведенного: {$_.Name +" Drive: Used: "+"{0:N2}" -f($_.Used/1gb) + " Free: "+"{0:N2}" -f($_.Free/1gb) + " Total: "+"{0:N2}" -f(($_.used/1gb) + ($_.Free/1gb));

Где Drive, Used, Free, Total text output - я хотел бы добавить какой-то передний план и фон, но я не могу понять, как это сделать. .

Полный сценарий: Get-PSDrive | Where-Object{$_.Free -gt 1} | ForEach-Object{$count = 0 ; "`n" }{$_.Name + " Drive: Used: " +"{0:N2}" -f($_.Used/1gb) + " Free: "+"{0:N2}" -f($_.Free/1gb) + " Total: "+"{0:N2}" -f(($_.used/1gb) + ($_.Free/1gb)); $count = $count + $_.Free;}{Write-Host "Total Free Space: " ("{0:N2}" -f($count/1gb)) -ForegroundColor White -BackgroundColor Black}

Ответы [ 2 ]

1 голос
/ 08 мая 2020

Windows 10 + PowerShell 5.1 и более поздних версий по умолчанию поддерживает escape-последовательности ANSI.

escape-код ANSI #DOS и Windows - Википедия

и вы необходимо использовать специальный символ для [esc] в PowerShell.

# PowerShell version 5
"$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

# PowerShell version 6+
"`e[30;41m YOUR_TEXT_HERE `e[0m"

Ссылки

0 голосов
/ 08 мая 2020

Можно сделать цвет без узла записи, используя ...

Свойство PSHostUserInterface.RawUI

$host.UI.RawUI.ForegroundColor = 'YourColorChoice'
$host.UI.RawUI.BackgroundColor = 'YourColorChoice'

... во всех версиях PowerShell. См. Эту статью.

Или используя пространство имен. Net ...

[console]::ForegroundColor = 'YourColorChoice'
[console]::BackgroundColor = 'YourColorChoice'

... во всех версиях PowerShell. См. Эту статью .

Вы уже указывали на материал Ansi / VT в PowerShell v5x.

либо напишите свои собственные функции, чтобы использовать их, либо знайте, что есть для этого варианта использования доступно несколько модулей.

Find-Module -Name '*color*' | Format-Table -AutoSize
<#
# Results
Version Name                    Repository Description                                                                                                                     
------- ----                    ---------- -----------                                                                                                                     
0.87    PSWriteColor            PSGallery  Write-Color is a wrapper around Write-Host allowing you to create nice looking scripts, with colorized output. It provides ea...
2.2.0   Get-ChildItemColor      PSGallery  Get-ChildItemColor provides colored versions of Get-ChildItem Cmdlet and Get-ChildItem | Format-Wide (ls equivalent)            
1.5     ISEColorTheme.Cmdlets   PSGallery  A collection of Powershell functions that expand the PowerShell ISE themeing capability to the command line. These functions ...
1.0.0.0 PSColor                 PSGallery  Provides basic color highlighting for files, services, select-string etc....                                                    
0.1.0.0 AnsiColorOut            PSGallery  ANSI color escape sequences for console output.                                                                                 
1.1.2   DirColors               PSGallery  Provides dircolors-like functionality to all System.IO.FilesystemInfo formatters                                                
1.3.0   PSColors                PSGallery  Nice prompt coloring for PowerShell                                                                                             
1.0.6   ColoredText             PSGallery  The cutting edge API for text coloring and highlighting in powershell.                                                          
1.0     SystemColorsGrid        PSGallery  Shows a pretty grid filled with system colors, their names, hex codes and rgb codes.                                            
1.3.0   PSColorText             PSGallery  Provides a simpler way of writing coloured text to the host.                                                                    
1.0.0   xColors                 PSGallery  Import xColors.net themes to Windows                                                                                            
1.0.0.1 psWriteInformationColor PSGallery  Performs true full-color write-information                                                                                      
0.0.1   ColorMode               PSGallery  Commandlets to control windows color scheme (dark/light)                                                                        
1.0.3   ColorizedHost           PSGallery  PowerShell modules that provides a function to write text to console with specified words highlighted in colors.                
1.0     Write-ColoredOutput     PSGallery  Writes output to pipeline yet capable to give colored output to the screen                                                      
0.0.6   PowerColorLS            PSGallery  List information about files and directories (the current directory by default)....                                             
1.0.0   PSColorizer             PSGallery  Outputs color-formatted messages to console. 
#>

PSWriteColor - это тот, который я бы рекомендовал. См. Эту статью об этом . Хотя на самом деле это модуль-оболочка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...