programing

쓰기 출력을 사용할 때 글꼴 색을 지정하는 방법이 있습니까?

iphone6s 2023. 8. 20. 10:32
반응형

쓰기 출력을 사용할 때 글꼴 색을 지정하는 방법이 있습니까?

쓰기 출력을 통해 상태 출력을 제공하는 파워셸 스크립트가 있습니다.출력이 캡처되어 다음과 같은 로그 파일에 기록될 수 있기 때문에 의도적으로 write-host를 사용하지 않습니다.

./myscript.ps1 | out-file log.txt

그러나 출력이 리디렉션되지 않을 경우 스크립트가 다양한 상태 메시지를 생성하기 때문에 콘솔에 컬러 출력이 있으면 좋습니다.쓰기 호스트에서 컬러 출력이 가능하지만 상태 메시지는 파이프 가능해야 합니다.

이 문제를 해결할 방법이 있습니까?

저는 이 추가 기능을 시도해 보았는데 기본적으로 잘 작동합니다.

function Write-ColorOutput($ForegroundColor)
{
    # save the current color
    $fc = $host.UI.RawUI.ForegroundColor

    # set the new color
    $host.UI.RawUI.ForegroundColor = $ForegroundColor

    # output
    if ($args) {
        Write-Output $args
    }
    else {
        $input | Write-Output
    }

    # restore the original color
    $host.UI.RawUI.ForegroundColor = $fc
}

# test
Write-ColorOutput red (ls)
Write-ColorOutput green (ls)
ls | Write-ColorOutput yellow

이 특정 테스트의 결과는 약간 웃깁니다. 빨간색, 녹색 및 노란색으로 줄이 표시되지만 테이블 헤더는 빨간색으로 표시됩니다. 즉, 함수의 첫 번째 호출 색상입니다.

방법:

function Green
{
    process { Write-Host $_ -ForegroundColor Green }
}

function Red
{
    process { Write-Host $_ -ForegroundColor Red }
}

Write-Output "this is a test" | Green
Write-Output "this is a test" | Red

enter image description here

파이프라인의 결과와 콘솔의 상태 메시지를 구분합니다.

예를 들어 스크립트에서 다음과 같은 기능을 사용합니다.

function write-status( $status ){
   $status | write-host -fore green -back red;  #send a status msg to the console
   $status | write-output; #send a status object down the pipe
}

또한 스크립트에서 상태 메시지를 출력하려면 write-host를 통해 다음 cmdlet 중 하나를 사용하는 것이 좋습니다.

  • 쓰기 시작한
  • 쓰기 오류
  • 쓰기 전용의
  • 쓰기 경고

이러한 상태 메시지의 모양은 사용된 cmdlet에 따라 달라집니다.또한 $(warning|error|verbose|debug) 기본 설정 변수를 사용하여 특정 수준의 상태를 사용하지 않도록 설정하거나 -(warning|error|verbose|debug) 변수 공통 cmdlet 매개 변수를 사용하여 특정 상태 메시지를 캡처할 수 있습니다.

저도 같은 문제가 있었기 때문에 제가 생각하는 솔루션을 공유합니다.

Write-ColorOutput "Hello" Green Black -NoNewLine
Write-ColorOutput " World" Red

사용할 cmdlet입니다.

function Write-ColorOutput
{
    [CmdletBinding()]
    Param(
         [Parameter(Mandatory=$False,Position=1,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][Object] $Object,
         [Parameter(Mandatory=$False,Position=2,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][ConsoleColor] $ForegroundColor,
         [Parameter(Mandatory=$False,Position=3,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][ConsoleColor] $BackgroundColor,
         [Switch]$NoNewline
    )    

    # Save previous colors
    $previousForegroundColor = $host.UI.RawUI.ForegroundColor
    $previousBackgroundColor = $host.UI.RawUI.BackgroundColor

    # Set BackgroundColor if available
    if($BackgroundColor -ne $null)
    { 
       $host.UI.RawUI.BackgroundColor = $BackgroundColor
    }

    # Set $ForegroundColor if available
    if($ForegroundColor -ne $null)
    {
        $host.UI.RawUI.ForegroundColor = $ForegroundColor
    }

    # Always write (if we want just a NewLine)
    if($Object -eq $null)
    {
        $Object = ""
    }

    if($NoNewline)
    {
        [Console]::Write($Object)
    }
    else
    {
        Write-Output $Object
    }

    # Restore previous colors
    $host.UI.RawUI.ForegroundColor = $previousForegroundColor
    $host.UI.RawUI.BackgroundColor = $previousBackgroundColor
}

이 게시물이 오래된 것은 알지만, 밖에 있는 누군가에게 도움이 될 수 있습니다.

저는 색깔을 바꾸고 싶었지만 받아들여진 답은 최선의 해결책이 아니었습니다.내가 보기에 다음 코드는 기본 PowerShell 기능을 활용하기 때문에 더 나은 솔루션입니다.

편집:

# Print User message using String Array $message
function PrintMessageToUser {
    param(
        [Parameter( `
            Mandatory=$True, `
            Valuefrompipeline = $true)]
        [String]$message
    )
    begin {
        $window_private_data = (Get-Host).PrivateData;
        # saving the original colors
        $saved_background_color = $window_private_data.VerboseBackgroundColor
        $saved_foreground_color = $window_private_data.VerboseForegroundColor
        # setting the new colors
        $window_private_data.VerboseBackgroundColor = 'Black';
        $window_private_data.VerboseForegroundColor = 'Red';
    }
    process {
        foreach ($Message in $Message) {
            # Write-Host Considered Harmful - see http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/
            # first way how to correctly write it
            #Write-host $message;
            Write-Verbose -Message $message -Verbose;
            # second correct way how to write it
            #$VerbosePreference = "Continue"
            #Write-Verbose $Message;
        }
    }
    end {
      $window_private_data.VerboseBackgroundColor = $saved_background_color;
      $window_private_data.VerboseForegroundColor = $saved_foreground_color;
    }

} # end PrintMessageToUser

저도 같은 문제가 있습니다. 화면별로 색상을 대화식으로 기록하고 자동으로 파일로 출력을 보내야 합니다.

제 해결책은 파라미터를 사용하여 출력 유형('화면' 또는 '파일')을 표시한 다음 함수가 출력을 렌더링하는 방법을 결정할 수 있습니다.

function Write-Color([String[]]$Text, [ConsoleColor[]]$Color, [ConsoleColor]$BackgroundColor = ([console]::BackgroundColor), $OutputType='Screen') {
    switch ($OutputType) {
        'Screen' { 
            for ($i = 0; $i -lt $Text.Length; $i++) {
                Write-Host $Text[$i] -Foreground $Color[$i] -NoNewLine -BackgroundColor $BackgroundColor
            }
            Write-Host
            break
        }
        'File' {
            # Assuming $OFS built-in Variable is an space
            write-output "$Text"
            break
        }
        Default {
            throw '$OutputType must be "Screen" or "File".'
        }
    }
}

$CodeBlock = {
    param ($OutputType)
    Write-Color -T "=== STARTING ===" -C Cyan -B Gray -O $OutputType
    Write-Color -T 'Date: ', (Get-Date).ToString('yyyy-MM-dd hh:mm:ss') -C Green, Yellow -O $OutputType
    Write-Color -T 'Processing..' -C Cyan -O $OutputType
    Write-Color -T 'Date: ', (Get-Date).AddSeconds(3).ToString('yyyy-MM-dd hh:mm:ss') -C Green, Yellow -O $OutputType
    Write-Color -T "=== ENDING ===" -C Cyan -B Gray -O $OutputType
}

$Dir = 'D:\Tmp'  # Set your output directory

#### Screen Test ####

& $CodeBlock -OutputType 'Screen'
& $CodeBlock -OutputType 'File'

### File Test ####

# This file have unwanted newlines, notice the IO redirection with "*>"
& $CodeBlock -OutputType 'Screen' *> "$Dir\Screen.log"

& $CodeBlock -OutputType 'File' > "$Dir\File.log"

언급URL : https://stackoverflow.com/questions/4647756/is-there-a-way-to-specify-a-font-color-when-using-write-output

반응형