Multiple foreground colors in PowerShell in one command

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

    Here is small a function I wrote to output colored text (it is actually smaller, but I rewrote it to be more understandable):

    function Write-Color() {
        Param (
            [string] $text = $(Write-Error "You must specify some text"),
            [switch] $NoNewLine = $false
        )
    
        $startColor = $host.UI.RawUI.ForegroundColor;
    
        $text.Split( [char]"{", [char]"}" ) | ForEach-Object { $i = 0; } {
            if ($i % 2 -eq 0) {
                Write-Host $_ -NoNewline;
            } else {
                if ($_ -in [enum]::GetNames("ConsoleColor")) {
                    $host.UI.RawUI.ForegroundColor = ($_ -as [System.ConsoleColor]);
                }
            }
    
            $i++;
        }
    
        if (!$NoNewLine) {
            Write-Host;
        }
        $host.UI.RawUI.ForegroundColor = $startColor;
    }
    

    It's quite simple to use: just use Write-Color "your text" and add some color name between curly brackets where you want the text to be colored.

    Examples:

    `Write-Color "Hello, {red}my dear {green}friend !"` will output
    

    Script screenshot

    You can put it in your $profile file to use it in a simple PowerShell prompt, or just add it to some scripts.

提交回复
热议问题