Multiple foreground colors in PowerShell in one command

后端 未结 13 1892
难免孤独
难免孤独 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条回答
  •  猫巷女王i
    2020-11-28 07:57

    This code is available with a different number of arguments: Text, ForeGroundColor, and BackGroundColor.

    Each colorlist is used with a rotate implementation:

    function Write-Color([String[]]$Text, [ConsoleColor[]]$ForeGroundColor, [ConsoleColor[]]$BackGroundColor) {
        for ($i = 0; $i -lt $Text.Length; $i++) {
            $Color = @{}
            if ($ForeGroundColor -and $BackGroundColor){
                $Color = @{
                    ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
                    BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
                }
            } elseif ($ForeGroundColor) {
                $Color = @{
                    ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
                }
            } elseif ($BackGroundColor) {
                $Color = @{
                    BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
                }
            }
            Write-Host $Text[$i] @color -NoNewLine
        }
        Write-Host
    }
    

    Log usage:

    Write-Color "Check color list...".PadRight(50), '[', '   OK   ', ']' -fore cyan, White, green, white
    Write-Color "Red Check is good...".PadRight(50), '[' ,' ERROR! ', ']' -fore cyan, White, red, white
    Write-Color "Write-Color is cool !".PadRight(50), '[', '  WARN  ', ']' -fore cyan, White, Yellow, white
    

    List Usage (just 2 backGroundColor and 4 foreGroundColor):

    Write-Color (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -ForeGroundColor cyan, yellow, magenta, red -BackGroundColor gray, black
    

    Standard Write-Host

    Write-Host (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -BackgroundColor gray
    

提交回复
热议问题