itsource

하나의 명령으로 PowerShell의 여러 전경색 표시

mycopycode 2023. 8. 10. 18:48
반응형

하나의 명령으로 PowerShell의 여러 전경색 표시

저는 하나의 문장으로 다양한 전경색을 출력하고 싶습니다.

PS C:\> Write-Host "Red" -ForegroundColor Red
Red

이 출력은 빨간색입니다.

PS C:\> Write-Host "Blue" -ForegroundColor Blue
Blue

이 출력은 파란색입니다.

PS C:\> Write-Host "Red", "Blue" -ForegroundColor Red, Blue
Red Blue

이 출력은 자홍색이지만, 하나의 명령어를 통해 빨간색은 빨간색, 파란색은 파란색을 원합니다.내가 어떻게 그럴 수 있을까?

쓰기-색상 명령이나 색상을 변경하는 인라인 토큰을 찾는 명령을 롤할 수 있습니다.이것이 BBS 시절에 ANSI 이스케이프 시퀀스가 작동하던 방식입니다.

그러나 다음과 같은 작업을 통해 원하는 것을 달성할 수 있습니다.

Write-Host "Red " -f red -nonewline; Write-Host "Blue " -f blue;

여기 당신이 요청한 것을 수행하는 간단한 작은 기능이 있습니다.

function Write-Color([String[]]$Text, [ConsoleColor[]]$Color) {
    for ($i = 0; $i -lt $Text.Length; $i++) {
        Write-Host $Text[$i] -Foreground $Color[$i] -NoNewLine
    }
    Write-Host
}

Write-Color -Text Red,White,Blue -Color Red,White,Blue

편집(2018년 5월 7일):Write-Color를 0.5업데이트하여 모듈로 게시했습니다.또한 현재 github에 코드가 게시되어 있습니다.

0.5의 변경 사항:

  • 추가된 배경색
  • 단축 코드에 별칭 T/B/C 추가
  • 함수에 별칭 추가("WC"와 함께 사용 가능)
  • 모듈 게시에 대한 수정 사항

0.4의 변화

  • 작은 문제들을 해결함
  • 모듈로 게시됨

리소스 링크:

게시된 모듈 덕분에 아래와 같은 코드를 쉽게 사용할 수 있습니다.

Install-Module PSWriteColor
Write-Color -Text "Some","Text" -Color Yellow,Red

더 이상 코드를 복사/붙여넣을 필요가 없습니다.즐거운 시간 되세요.

이전 코드는 아래와 같습니다.최신 코드의 경우 위의 링크를 사용하는 것이 좋습니다.

편집(2018년 4월 9일):Write-Color를 v0.3으로 업데이트했습니다.제가 쓰기-색상을 유지하고 있는 사이트에서 언제든지 구입하십시오.약간의 변화가 있습니다.포함 - 줄 없음 및 - 시간 표시 옵션.

편집(2017년 6월): 새 버전으로 업데이트, 로깅 목적으로 파일에 로깅 추가

Josh 방법이 너무 좋아서 제가 가서 필요에 맞게 조금 확장했습니다.저는 전체 스토리와 사용을 위해 다양한 색상의 PowerShell을 포맷하는 방법을 블로그 게시물에 썼습니다.

    function Write-Color([String[]]$Text, [ConsoleColor[]]$Color = "White", [int]$StartTab = 0, [int] $LinesBefore = 0,[int] $LinesAfter = 0, [string] $LogFile = "", $TimeFormat = "yyyy-MM-dd HH:mm:ss") {
    # version 0.2
    # - added logging to file
    # version 0.1
    # - first draft
    # 
    # Notes:
    # - TimeFormat https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

    $DefaultColor = $Color[0]
    if ($LinesBefore -ne 0) {  for ($i = 0; $i -lt $LinesBefore; $i++) { Write-Host "`n" -NoNewline } } # Add empty line before
    if ($StartTab -ne 0) {  for ($i = 0; $i -lt $StartTab; $i++) { Write-Host "`t" -NoNewLine } }  # Add TABS before text
    if ($Color.Count -ge $Text.Count) {
        for ($i = 0; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine } 
    } else {
        for ($i = 0; $i -lt $Color.Length ; $i++) { Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine }
        for ($i = $Color.Length; $i -lt $Text.Length; $i++) { Write-Host $Text[$i] -ForegroundColor $DefaultColor -NoNewLine }
    }
    Write-Host
    if ($LinesAfter -ne 0) {  for ($i = 0; $i -lt $LinesAfter; $i++) { Write-Host "`n" } }  # Add empty line after
    if ($LogFile -ne "") {
        $TextToFile = ""
        for ($i = 0; $i -lt $Text.Length; $i++) {
            $TextToFile += $Text[$i]
        }
        Write-Output "[$([datetime]::Now.ToString($TimeFormat))]$TextToFile" | Out-File $LogFile -Encoding unicode -Append
    }
}


Write-Color -Text "Red ", "Green ", "Yellow " -Color Red,Green,Yellow

Write-Color -Text "This is text in Green ",
                   "followed by red ",
                   "and then we have Magenta... ",
                   "isn't it fun? ",
                   "Here goes DarkCyan" -Color Green,Red,Magenta,White,DarkCyan

Write-Color -Text "This is text in Green ",
                   "followed by red ",
                   "and then we have Magenta... ",
                   "isn't it fun? ",
                   "Here goes DarkCyan" -Color Green,Red,Magenta,White,DarkCyan -StartTab 3 -LinesBefore 1 -LinesAfter 1

Write-Color "1. ", "Option 1" -Color Yellow, Green
Write-Color "2. ", "Option 2" -Color Yellow, Green
Write-Color "3. ", "Option 3" -Color Yellow, Green
Write-Color "4. ", "Option 4" -Color Yellow, Green
Write-Color "9. ", "Press 9 to exit" -Color Yellow, Gray -LinesBefore 1



Write-Color -LinesBefore 2 -Text "This little ","message is ", "written to log ", "file as well." -Color Yellow, White, Green, Red, Red -LogFile "C:\testing.txt" -TimeFormat "yyyy-MM-dd HH:mm:ss"
Write-Color -Text "This can get ","handy if ", "want to display things, and log actions to file ", "at the same time." -Color Yellow, White, Green, Red, Red -LogFile "C:\testing.txt"

How to format PowerShell with Multiple Colors

이것은 실제로 Josh 스크립트에 대한 추가적인 확인과 기능을 제공합니다.

https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/17/writing-output-with-powershell/ 에서 훨씬 더 쉬운 옵션을 찾았습니다.

기본적으로 첫 번째 쓰기 호스트에는 -NewLine 없음 옵션이 포함됩니다.이렇게 하면 새 선이 형성되지 않습니다.다음 쓰기 호스트는 이전 텍스트 바로 뒤에 추가됩니다.각 쓰기 호스트에는 전경색 옵션이 있습니다.이 작업은 필요한 각 색상 변경에 대해 반복할 수 있습니다.

세 가지 색상이 있는 텍스트의 한 줄 예제:

write-host "Your text here " -ForeGroundColor Red -NoNewLine
write-host "some other text here " -ForeGroundColor Yellow -NoNewLine
write-host "And the last text here."

첫 번째와 두 번째 쓰기 호스트에는 텍스트 뒤에 공백이 있습니다.PowerShell은 텍스트를 연결하거나 결합하는 것이 아니라 커서를 다음 줄로 이동하지 않는 것입니다.

이 기능은 다양한 통사 당을 제공합니다.

function color-Write
{
    # DO NOT SPECIFY param(...)
    #    we parse colors ourselves.

    $allColors = ("-Black",   "-DarkBlue","-DarkGreen","-DarkCyan","-DarkRed","-DarkMagenta","-DarkYellow","-Gray",
                  "-Darkgray","-Blue",    "-Green",    "-Cyan",    "-Red",    "-Magenta",    "-Yellow",    "-White")
    $foreground = (Get-Host).UI.RawUI.ForegroundColor # current foreground
    $color = $foreground
    [bool]$nonewline = $false
    $sofar = ""
    $total = ""

    foreach($arg in $args)
    {
        if ($arg -eq "-nonewline") { $nonewline = $true }
        elseif ($arg -eq "-foreground")
        {
            if ($sofar) { Write-Host $sofar -foreground $color -nonewline }
            $color = $foregrnd
            $sofar = ""
        }
        elseif ($allColors -contains $arg)
        {
            if ($sofar) { Write-Host $sofar -foreground $color -nonewline }
            $color = $arg.substring(1)
            $sofar = ""
        }
        else
        {
            $sofar += "$arg "
            $total += "$arg "
        }
    }
    # last bit done special
    if (!$nonewline)
    {
        Write-Host $sofar -foreground $color
    }
    elseif($sofar)
    {
        Write-Host $sofar -foreground $color -nonewline
    }
}

예:

color-Write This is normal text
color-Write Normal -Red Red -White White -Blue Blue -ForeGround Normal

전경색과 배경색 모두에 대해 문자열에 색상 명령을 포함할 수 있는 고급 함수를 아래에서 찾습니다.

Write-HostColored "I'm #green#green#, I'm #red#red#, and I'm #blue:white#blue on white#."

위의 산출물:

sample output

기본 전경 및 배경색을 사용할 수 있습니다.-ForegroundColor그리고.-BackgroundColor다음 구문을 사용하여 쓸 문자열에 하나 이상의 색상 지정을 포함할 수 있습니다.

#<fgcolor>[:<bgcolor>]#<text>#

<fgcolor>그리고.<bgcolor>한 유해야합다이어야 .[ConsoleColor]: 값):green또는white(대소문자는 상관 없음).색상 사양에 따른 다음까지의 모든 사항#또는 암묵적으로 문자열의 끝까지 해당 색상으로 작성됩니다.


Write-HostColored소스 코드(PSv2+):

<#
.SYNOPSIS
A wrapper around Write-Host that supports selective coloring of
substrings via embedded coloring specifications.

.DESCRIPTION
In addition to accepting a default foreground and background color,
you can embed one or more color specifications in the string to write,
using the following syntax:
#<fgcolor>[:<bgcolor>]#<text>#

<fgcolor> and <bgcolor> must be valid [ConsoleColor] values, such as 'green' or 'white' (case does not matter).
Everything following the color specification up to the next '#', or impliclitly to the end of the string,
is written in that color.

Note that nesting of color specifications is not supported.
As a corollary, any token that immediately follows a color specification is treated
as text to write, even if it happens to be a technically valid color spec too.
This allows you to use, e.g., 'The next word is #green#green#.', without fear
of having the second '#green' be interpreted as a color specification as well.

.PARAMETER ForegroundColor
Specifies the default text color for all text portions
for which no embedded foreground color is specified.

.PARAMETER BackgroundColor
Specifies the default background color for all text portions
for which no embedded background color is specified.

.PARAMETER NoNewline
Output the specified string withpout a trailing newline.

.NOTES
While this function is convenient, it will be slow with many embedded colors, because,
behind the scenes, Write-Host must be called for every colored span.

.EXAMPLE
Write-HostColored "#green#Green foreground.# Default colors. #blue:white#Blue on white."

.EXAMPLE
'#black#Black on white (by default).#Blue# Blue on white.' | Write-HostColored -BackgroundColor White

#>
function Write-HostColored() {
    [CmdletBinding()]
    param(
        [parameter(Position=0, ValueFromPipeline=$true)]
        [string[]] $Text
        ,
        [switch] $NoNewline
        ,
        [ConsoleColor] $BackgroundColor = $host.UI.RawUI.BackgroundColor
        ,
        [ConsoleColor] $ForegroundColor = $host.UI.RawUI.ForegroundColor
    )

    begin {
        # If text was given as a parameter value, it'll be an array.
        # Like Write-Host, we flatten the array into a single string
        # using simple string interpolation (which defaults to separating elements with a space,
        # which can be changed by setting $OFS).
        if ($Text -ne $null) {
            $Text = "$Text"
        }
    }

    process {
        if ($Text) {

            # Start with the foreground and background color specified via
            # -ForegroundColor / -BackgroundColor, or the current defaults.
            $curFgColor = $ForegroundColor
            $curBgColor = $BackgroundColor

            # Split message into tokens by '#'.
            # A token between to '#' instances is either the name of a color or text to write (in the color set by the previous token).
            $tokens = $Text.split("#")

            # Iterate over tokens.
            $prevWasColorSpec = $false
            foreach($token in $tokens) {

                if (-not $prevWasColorSpec -and $token -match '^([a-z]*)(:([a-z]+))?$') { # a potential color spec.
                    # If a token is a color spec, set the color for the next token to write.
                    # Color spec can be a foreground color only (e.g., 'green'), or a foreground-background color pair (e.g., 'green:white'), or just a background color (e.g., ':white')
                    try {
                        $curFgColor = [ConsoleColor] $matches[1]
                        $prevWasColorSpec = $true
                    } catch {}
                    if ($matches[3]) {
                        try {
                            $curBgColor = [ConsoleColor] $matches[3]
                            $prevWasColorSpec = $true
                        } catch {}
                    }
                    if ($prevWasColorSpec) {
                        continue
                    }
                }

                $prevWasColorSpec = $false

                if ($token) {
                    # A text token: write with (with no trailing line break).
                    # !! In the ISE - as opposed to a regular PowerShell console window,
                    # !! $host.UI.RawUI.ForegroundColor and $host.UI.RawUI.ForegroundColor inexcplicably
                    # !! report value -1, which causes an error when passed to Write-Host.
                    # !! Thus, we only specify the -ForegroundColor and -BackgroundColor parameters
                    # !! for values other than -1.
                    # !! Similarly, PowerShell Core terminal windows on *Unix* report -1 too.
                    $argsHash = @{}
                    if ([int] $curFgColor -ne -1) { $argsHash += @{ 'ForegroundColor' = $curFgColor } }
                    if ([int] $curBgColor -ne -1) { $argsHash += @{ 'BackgroundColor' = $curBgColor } }
                    Write-Host -NoNewline @argsHash $token
                }

                # Revert to default colors.
                $curFgColor = $ForegroundColor
                $curBgColor = $BackgroundColor

            }
        }
        # Terminate with a newline, unless suppressed
        if (-not $NoNewLine) { write-host }
    }
}

다음은 컬러 텍스트를 출력하기 위해 작성한 작은 함수입니다(실제로는 더 작지만 더 이해하기 쉽도록 다시 작성했습니다).

function Write-Color() {
    Param (
        [string] $text = $(Write-Error "You must specify some text"),
        [switch] $NoNewLine = $false
    )

    $startColor = $host.UI.RawUI.ForegroundColor;

    $text.Split( [char]"{", [char]"}" ) | ForEach-Object { $i = 0; } {
        if ($i % 2 -eq 0) {
            Write-Host $_ -NoNewline;
        } else {
            if ($_ -in [enum]::GetNames("ConsoleColor")) {
                $host.UI.RawUI.ForegroundColor = ($_ -as [System.ConsoleColor]);
            }
        }

        $i++;
    }

    if (!$NoNewLine) {
        Write-Host;
    }
    $host.UI.RawUI.ForegroundColor = $startColor;
}

매우 . 사법은간다니합단매우를 사용하세요. 사용하기만 하면 됩니다.Write-Color "your text"텍스트에 색상을 지정할 대괄호 사이에 색상 이름을 추가합니다.

예:

`Write-Color "Hello, {red}my dear {green}friend !"` will output

스크립트 스크린샷

당신은 그것을 당신의 것에 넣을 수 있습니다.$profile파일을 사용하여 간단한 PowerShell 프롬프트에서 사용하거나 일부 스크립트에 추가할 수 있습니다.

이 코드는 다른 수의 인수와 함께 사용할 수 있습니다.텍스트, 전경색 및 배경색입니다.

각 색상 리스트는 회전 구현과 함께 사용됩니다.

function Write-Color([String[]]$Text, [ConsoleColor[]]$ForeGroundColor, [ConsoleColor[]]$BackGroundColor) {
    for ($i = 0; $i -lt $Text.Length; $i++) {
        $Color = @{}
        if ($ForeGroundColor -and $BackGroundColor){
            $Color = @{
                ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
                BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
            }
        } elseif ($ForeGroundColor) {
            $Color = @{
                ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
            }
        } elseif ($BackGroundColor) {
            $Color = @{
                BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
            }
        }
        Write-Host $Text[$i] @color -NoNewLine
    }
    Write-Host
}

로그 사용량:

Write-Color "Check color list...".PadRight(50), '[', '   OK   ', ']' -fore cyan, White, green, white
Write-Color "Red Check is good...".PadRight(50), '[' ,' ERROR! ', ']' -fore cyan, White, red, white
Write-Color "Write-Color is cool !".PadRight(50), '[', '  WARN  ', ']' -fore cyan, White, Yellow, white

Enter image description here

사용 목록 표시(2개의 backGroundColor와 4개의 forGroundColor만):

Write-Color (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -ForeGroundColor cyan, yellow, magenta, red -BackGroundColor gray, black

Enter image description here

표준 쓰기 호스트

Write-Host (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -BackgroundColor gray

Enter image description here

이것도 효과가 있어요...

Write-Host "Don't forget to " -ForegroundColor Yellow -NoNewline; Write-Host "CALL YOUR MOM " -ForegroundColor Red -NoNewline; Write-Host "every day!" -ForegroundColor Yellow

이것에 대한 약간의 수정...버전 2를 사용하여 로깅을 제거한 다음 -NoNewLine for Write-Host와 유사한 부울 매개 변수를 추가했습니다.저는 특히 같은 줄에 색상을 변경하고 사용자 입력을 요청하는 기능을 추가하여 사용자가 아무것도 입력하지 않을 경우 기본 답변을 강조하려고 했습니다.

Write-HostColored(쓰기 호스트 색상)에서 사용할 수 있다는 것을 알고 있습니다(이전 답변).하지만 가끔은 더 간단한 코드를 원할 때도 있습니다

function Write-Color([String[]]$Text, [ConsoleColor[]]$Color = "White", [int]$StartTab = 0, [int] $LinesBefore = 0,[int] $LinesAfter = 0, [bool] $NewLine = $True) {

    # Notes:
    # - TimeFormat https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
    #
    # Example:  Write-Color -Text "Red ", "Green ", "Yellow " -Color Red,Green,Yellow -NewLine $False
    #
    $DefaultColor = $Color[0]
    if ($LinesBefore -ne 0) {
        for ($i = 0; $i -lt $LinesBefore; $i++) {
            Write-Host "`n" -NoNewline
        }
    } # Add empty line before

    if ($StartTab -ne 0) {
        for ($i = 0; $i -lt $StartTab; $i++) {
            Write-Host "`t" -NoNewLine
        }
    }  # Add TABS before text

    if ($Color.Count -ge $Text.Count) {
        for ($i = 0; $i -lt $Text.Length; $i++) {
            Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine
        }
    }
    else {
        for ($i = 0; $i -lt $Color.Length ; $i++) {
            Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine
        }
        for ($i = $Color.Length; $i -lt $Text.Length; $i++) {
            Write-Host $Text[$i] -ForegroundColor $DefaultColor -NoNewLine
        }
    }

    if ($NewLine -eq $False) {
        Write-Host -NoNewLine
    }
    else {
        Write-Host
    }

    if ($LinesAfter -ne 0) {
        for ($i = 0; $i -lt $LinesAfter; $i++) {
            Write-Host "`n"
        }
    }  # Add empty line after

}  # END FUNCTION Write-Color

제가 달성하고자 했던 것의 예:

Write-Color -Text "Is this correct? ","[y]","/n" -Color White, Magenta, White -NewLine $False ; Read-Host " "

그래서 제가 생각해낸 것이 있습니다.누군가에게 도움이 되길 바랍니다.

$e = "$([char]27)"

enum ANSIFGColors {
  Black   = 30
  Red     = 91
  Green   = 92
  Yellow  = 93
  Blue    = 94
  Magenta = 95
  Cyan    = 96
  White   = 97
}

enum ANSIBGColors {
  Black   = 40
  Red     = 41
  Green   = 42
  Yellow  = 103
  Blue    = 44
  Magenta = 105
  Cyan    = 46
  White   = 107
}

function Colorize-Text {
  param (
    [string]$StringToColor,
    [ANSIFGColors]$TextColor,
    [ANSIBGColors]$BackgroundColor
  )

  $retValue = $null

  if ($BackgroundColor -ne $null ) { $retValue = [string]"$e[$($TextColor.value__);$($BackgroundColor.value__)m$StringToColor$e[0m" }
  else                             { $retValue = [string]"$e[$($TextColor.value__)m$StringToColor$e[0m" }

  return $retValue

}

다음과 같이 사용할 수 있습니다.

$FirstVar = Colorize-Text -StringToColor "This is Green" -TextColor Green

$SecondVar = Colorize-Text -StringToColor "This is NOT Green" -TextColor Cyan -BackgroundColor Red

Write-host $FirstVar $SecondVar

아니면 당신이 선택한 다른 조합.

간단한 방법은 다음과 같습니다.

if ($help)
{

    Write-Host "     For the switch " -NoNewline; Write-Host " -userUniqueId" -ForegroundColor Green -NoNewline; Write-Host ", enter an email address or samaccountname (pin) so '-userUniqueId 123456' "
    Write-Host "";
    Write-Host "     For the switch " -NoNewline; Write-Host " -disableMFAForUser" -ForegroundColor Green -NoNewline; Write-Host ", enter an email address or samaccountname (pin) with the -userUniqueId and then '-disableMFAForUser $true' "
    Write-Host "";
    Write-Host "     For the switch " -NoNewline; Write-Host "-enableMFAForUser" -ForegroundColor Green -NoNewline; Write-Host ", enter an email address or samaccountname (pin) with the -userUniqueId and then '-enableMFAForUser $true' "
    Write-Host "";
    Write-Host "     For the switch " -NoNewline; Write-Host "-verifyAllMFAEnabled" -ForegroundColor Green -NoNewline; Write-Host ", enter '-verifyAllMFAEnabled $true' "
    Write-Host "";
    Write-Host "     For the switch " -NoNewline; Write-Host " -verifyAllMFADisabledSpecificUser" -ForegroundColor Green -NoNewline; Write-Host ", enter an email address or samaccountname (pin) and then '-verifyAllMFADisabledSpecificUser $true' "
    Write-Host "";

    return;
}

ISE의 Windows Server 2012 R2 박스에서 이 기능을 실행하려고 했는데 Jesse Chisholm의 기능이 어떤 이유로 실패했습니다(Get-Host).UI.RawUI.ForegroundColor는 -1이었습니다.이러한 현상을 방지하고 기능을 단순화하기 위해 다음과 같이 수정했습니다.

function Write-ColorText
{
    # DO NOT SPECIFY param(...)
    #    we parse colors ourselves.

    $allColors = ("-Black",   "-DarkBlue","-DarkGreen","-DarkCyan","-DarkRed","-DarkMagenta","-DarkYellow","-Gray",
                  "-Darkgray","-Blue",    "-Green",    "-Cyan",    "-Red",    "-Magenta",    "-Yellow",    "-White",
                   "-Foreground")

    $color = "Foreground"
    $nonewline = $false

    foreach($arg in $args)
    {
        if ($arg -eq "-nonewline")
        { 
            $nonewline = $true 
        }
        elseif ($allColors -contains $arg)
        {
            $color = $arg.substring(1)
        }
        else
        {
            if ($color -eq "Foreground")
            {
                Write-Host $arg -nonewline
            }
            else
            {
                Write-Host $arg -foreground $color -nonewline
            }
        }
    }

    Write-Host -nonewline:$nonewline
}

나는 이것이 오래된 게시물이라는 것을 알지만, 이것이 누군가에게 유용하기를 바라며, 제시가 나에게 이 멋진 기능을 제공해줘서 고마워요!!

만약 당신이 제 상황이라면, 저는 마이크로소프트 문서에서 콘솔 모드를 설정하는 평범한 바닐라 방법을 찾았습니다.cmd와 powershell 모두에서 256가지 색상의 ansi 콘솔 지원을 시작하고 종료하는 쉬운 방법은 다음과 같습니다.

// https://learn.microsoft.com/en-us/windows/console/setconsolemode
#include <Windows.h>
#include <iostream>
struct  console_data {
    HANDLE hstdin;
    DWORD  mode;

    DWORD start()
    {
        hstdin = GetStdHandle(STD_OUTPUT_HANDLE);
        GetConsoleMode(hstdin, &mode);
        if (!SetConsoleMode(hstdin, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
            DWORD E = GetLastError();
            std::cout << " Error #" << E << "in:"  __FUNCTION__ "\n";
            return GetLastError();
        }
        std::cout << "\033[1;14mReady.\e[0m\n";
        return 0;
    }

    void end()
    {
        SetConsoleMode(hstdin, mode);
    }
    ~console_data() {
        end();
    }
    //...
}RTConsole;

//...
int main()
{
   //... 
   RTConsole.start();
   std::cout << "\033[38;5;192m Should be 'Orange'\n";
   RTConsole.end();
   return 0;
}

https://learn.microsoft.com/en-us/windows/console/setconsolemode

참고: VS Code의 powershell 확장에 256가지 색상을 지원하는 방법을 찾지 못했습니다.

또 다른 "색상 쓰기" 기능은 다음과 같습니다.

  1. 색상 배열을 만드는 데 도움이 되는 도우미 기능 Get-WriteColors가 있습니다. (그렇지 않으면 [ConsoleColor]::흰색, [콘솔 색상]::빨간색 등)
  2. ForeColor와 BackColor 모두를 통해 독립적으로 반복 사이클합니다.
  3. 기본적으로 텍스트에서 '~' 마커를 사용하여 색상 변경을 나타냅니다.
  4. 색상 매개 변수 앞에 2개의 문자열이 지정된 경우 두 번째 문자열이 색상 변경 마커로 '~'을 대체합니다.
  5. -NewLine 스위치가 포함되어 있습니다.
function Get-WriteColors {
    param(
        [Parameter(Mandatory, Position = 0)]
        [ConsoleColor[]]$ColorSet
    )
    return $ColorSet
}
function Write-Colors {
    [CmdletBinding(DefaultParameterSetName = 'NoCCMarker')]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Text,
        [Parameter(Mandatory, Position = 1, ParameterSetName = 'HasCCMarker')]
        [string]$ColorChangeMarker,
        [Parameter(Mandatory, Position = 1, ParameterSetName = 'NoCCMarker')]
        [Parameter(Mandatory, Position = 2, ParameterSetName = 'HasCCMarker')]
        [ConsoleColor[]]$ForeColor,
        [Parameter(Position = 2, ParameterSetName = 'NoCCMarker')]
        [Parameter(Position = 3, ParameterSetName = 'HasCCMarker')]
        [ConsoleColor[]]$BackColor = @([ConsoleColor]::Black),
        [switch]$NoNewLine
    )
    $Marker = if($PsCmdlet.ParameterSetName -eq 'NoCCMarker') {'~'} else {$ColorChangeMarker}
    $TextList = $Text -Split $Marker
    for($t = 0; $t -lt $TextList.Count; $t++) {
        $f = $t % $ForeColor.Count
        $b = $t % $BackColor.Count
        Write-Host $TextList[$t] -ForegroundColor $ForeColor[$f] -BackgroundColor $BackColor[$b] -NoNewLine
    }
    if( -not $NoNewLine ) {Write-Host}
}

사용 예: 쓰기-색상에 대한 두 번째 호출은 기본값 '~'을 '#'로 바꿉니다.

$f = 'C:\Temp\TestPath\TestFile.TXT'
$d =[System.IO.Path]::GetPathRoot($f)
$p = [System.IO.Path]::GetDirectoryName($f).SubString($d.Length)
$n = [System.IO.Path]::GetFileNameWithoutExtension($f)
$x = [System.IO.Path]::GetExtension($f)
$dp = $d + $p
$nx = $n + $x
#    Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow,  Gray
# DarkGray,     Blue,     Green,     Cyan,     Red,     Magenta,     Yellow, White
$ForeColors = Get-WriteColors Yellow, White, Cyan, Yellow, Red
$BackColors = Get-WriteColors DarkBlue, black, black, black, black
Write-Colors "f:~ [~$f~]" $ForeColors $BackColors
Write-Colors "dp:#[#$dp#]#, #nx:#[#$nx#]" '#' $ForeColors $BackColors
Write-Colors "d:~ [~$d~]~, ~p:~[~$p~]~, ~n:~[~$n~]~, ~x:~[~$x~]" $ForeColors $BackColors

출력:

enter image description here

언급URL : https://stackoverflow.com/questions/2688547/multiple-foreground-colors-in-powershell-in-one-command

반응형