Multiple foreground colors in PowerShell in one command

后端 未结 13 1893
难免孤独
难免孤独 2020-11-28 07:19

I want to output many different foreground colors with one statement.

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

This output i

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 07:50

    I was trying to run this on a Windows Server 2012R2 box under ISE and the function by Jesse Chisholm was failing because for some reason (Get-Host).UI.RawUII.ForegroundColor was -1. To stop this happening and to simplify the function I little I modified it as follows:

    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
    }
    

    I know this is an old post but hopefully this is useful to somebody and thanks Jesse for giving me this wonderful function!!

提交回复
热议问题