Is there a way to specify a font color when using write-output

前端 未结 5 1596
抹茶落季
抹茶落季 2021-02-07 02:25

I have a powershell script that gives some status output via write-output. I am intentionally not using write-host because the output may be captured and writt

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 02:46

    I had the same problem, so I share my solution which I think works quite well:

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

    This is the Cmdlet to use it

    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
    }
    

提交回复
热议问题