Multiple foreground colors in PowerShell in one command

后端 未结 13 1888
难免孤独
难免孤独 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 08:01

    Slight modification to this one... I took version 2, removed the logging (because I don't want it), and then added a Boolean parameter, similar to -NoNewLine for Write-Host. I was specifically trying to add the ability to change the colors and prompt for user input on the same line so that I could highlight the default answer if the user does not enter anything.

    I realize this was available in Write-HostColored (in a previous answer)... but sometimes you just want simpler code...

    function Write-Color([String[]]$Text, [ConsoleColor[]]$Color = "White", [int]$StartTab = 0, [int] $LinesBefore = 0,[int] $LinesAfter = 0, [bool] $NewLine = $True) {
    
        # Notes:
        # - TimeFormat https://msdn.microsoft.com/en-us/library/8kb3ffffd4.aspx
        #
        # Example:  Write-Color -Text "Red ", "Green ", "Yellow " -Color Red,Green,Yellow -NewLine $False
        #
        $DefaultColor = $Color[0]
        if ($LinesBefore -ne 0) {
            for ($i = 0; $i -lt $LinesBefore; $i++) {
                Write-Host "`n" -NoNewline
            }
        } # Add empty line before
    
        if ($StartTab -ne 0) {
            for ($i = 0; $i -lt $StartTab; $i++) {
                Write-Host "`t" -NoNewLine
            }
        }  # Add TABS before text
    
        if ($Color.Count -ge $Text.Count) {
            for ($i = 0; $i -lt $Text.Length; $i++) {
                Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine
            }
        }
        else {
            for ($i = 0; $i -lt $Color.Length ; $i++) {
                Write-Host $Text[$i] -ForegroundColor $Color[$i] -NoNewLine
            }
            for ($i = $Color.Length; $i -lt $Text.Length; $i++) {
                Write-Host $Text[$i] -ForegroundColor $DefaultColor -NoNewLine
            }
        }
    
        if ($NewLine -eq $False) {
            Write-Host -NoNewLine
        }
        else {
            Write-Host
        }
    
        if ($LinesAfter -ne 0) {
            for ($i = 0; $i -lt $LinesAfter; $i++) {
                Write-Host "`n"
            }
        }  # Add empty line after
    
    }  # END FUNCTION Write-Color
    

    Sample of what I was trying to accomplish:

    Write-Color -Text "Is this correct? ","[y]","/n" -Color White, Magenta, White -NewLine $False ; Read-Host " "
    

提交回复
热议问题