2017-11-13 1 views
2

StringBuilder 객체에 색상이있는 선을 추가 할 수 있습니까?
나는 쓰기 호스트와 색상을 추가하는 방법을 알고 StringBuilderStringBuilder 객체에 색상 선을 삽입하는 방법

Write-Host "Line without a color" 
Write-Host "Line with red color" -ForegroundColor Red 

하지만하지 :

$sb = New-Object -TypeName "System.Text.StringBuilder" 
$sb.AppendLine("Line without a color") | Out-Null 
$sb.AppendLine("Line with red color") | Out-Null 
$sb.ToString() 

내가 함께 모든 라인을 잡아 그들 모두를 인쇄하는 것을 선호합니다.
StringBuilder은 좋은 방법이지만 색상이있는 선들도 필요합니다.
가능합니까?
enter image description here

내가 RTFString 빌더에 대해 뭔가 here을 읽을 수는 있지만 예상대로 나를 위해 작동하지 않았다

이 내가 StringBuilder와 싶어 출력

.

+2

'StringBuilder' 객체 색상의 어떤 개념이 없습니다. 색상을 원한다면 문자열 내에 이스케이프 코드를 삽입하고 문자열을 원하는 색상으로 출력해야합니다. –

+0

@ Bill_Stewart 당신은 작은 것을 어떻게 사용합니까? 문자열에 색상을 인쇄하는 몇 가지 기능을 찾았습니다. https://stackoverflow.com/questions/2688547/multiple-foreground-colors-in-powershell-in-one-command하지만 일부 기본 코드가있을 수 있습니다. "{color : # 8B0000}"이것은 빨간색 선입니다. – E235

+1

직접 작성해야합니다. 코드의 표시 부분에서는 포함 된 채색을 찾고 그대로 출력해야합니다. 이 작업을 수행 할 기본 제공 항목이 없습니다. 색상은 "출력 전용"기능입니다. –

답변

1

해결 방법 :

$sb = New-Object -TypeName "System.Text.StringBuilder" 
$sb.AppendLine("Line without a color") | Out-Null 
$sb.AppendLine("#color:red#Line with red color") | Out-Null 


$delim [email protected]([Environment]::NewLine, "\n") 
$sbLines = $sb.ToString().Split($delim, [System.StringSplitOptions]::None) 
foreach($line in $sbLines){ 


    if($line.StartsWith("#color:red#")){ 
     Write-Host $line.Split("#")[2] -ForegroundColor Red 
    } 
    else{ 
     Write-Host $line 
    } 
} 

더 일반적인 솔루션 :

<# 
.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 } 
    } 
} 


# MAIN 
$sb = New-Object -TypeName "System.Text.StringBuilder" 
$sb.AppendLine("Line without a color") | Out-Null 
$sb.AppendLine("#red#Line with red color") | Out-Null 

$delim [email protected]([Environment]::NewLine, "\n") 
$sbLines = $sb.ToString().Split($delim, [System.StringSplitOptions]::None) 
foreach($line in $sbLines){ 
    Write-HostColored $line 
} 
관련 문제