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

前端 未结 5 1592
抹茶落季
抹茶落季 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:55

    I have tried this extra function and it basically works fine:

    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
    

    The result of this particular test is a little bit funny though: we really get lines in red, green and yellow but the table header is in red, i.e. the color of the the first call of the function.

提交回复
热议问题