Multiple foreground colors in PowerShell in one command

后端 未结 13 1840
难免孤独
难免孤独 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:57

    This function provides different syntactic sugar:

    function color-Write
    {
        # 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 = (Get-Host).UI.RawUI.ForegroundColor # current foreground
        $color = $foreground
        [bool]$nonewline = $false
        $sofar = ""
        $total = ""
    
        foreach($arg in $args)
        {
            if ($arg -eq "-nonewline") { $nonewline = $true }
            elseif ($arg -eq "-foreground")
            {
                if ($sofar) { Write-Host $sofar -foreground $color -nonewline }
                $color = $foregrnd
                $sofar = ""
            }
            elseif ($allColors -contains $arg)
            {
                if ($sofar) { Write-Host $sofar -foreground $color -nonewline }
                $color = $arg.substring(1)
                $sofar = ""
            }
            else
            {
                $sofar += "$arg "
                $total += "$arg "
            }
        }
        # last bit done special
        if (!$nonewline)
        {
            Write-Host $sofar -foreground $color
        }
        elseif($sofar)
        {
            Write-Host $sofar -foreground $color -nonewline
        }
    }
    

    Examples:

    color-Write This is normal text
    color-Write Normal -Red Red -White White -Blue Blue -ForeGround Normal
    

提交回复
热议问题