Multiple foreground colors in PowerShell in one command

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

    So here's something I came up with. Hope it helps someone out.

    $e = "$([char]27)"
    
    enum ANSIFGColors {
      Black   = 30
      Red     = 91
      Green   = 92
      Yellow  = 93
      Blue    = 94
      Magenta = 95
      Cyan    = 96
      White   = 97
    }
    
    enum ANSIBGColors {
      Black   = 40
      Red     = 41
      Green   = 42
      Yellow  = 103
      Blue    = 44
      Magenta = 105
      Cyan    = 46
      White   = 107
    }
    
    function Colorize-Text {
      param (
        [string]$StringToColor,
        [ANSIFGColors]$TextColor,
        [ANSIBGColors]$BackgroundColor
      )
    
      $retValue = $null
    
      if ($BackgroundColor -ne $null ) { $retValue = [string]"$e[$($TextColor.value__);$($BackgroundColor.value__)m$StringToColor$e[0m" }
      else                             { $retValue = [string]"$e[$($TextColor.value__)m$StringToColor$e[0m" }
    
      return $retValue
    
    }
    

    Can be used thus;

    $FirstVar = Colorize-Text -StringToColor "This is Green" -TextColor Green
    
    $SecondVar = Colorize-Text -StringToColor "This is NOT Green" -TextColor Cyan -BackgroundColor Red
    
    Write-host $FirstVar $SecondVar
    

    Or whatever other combination you choose.

提交回复
热议问题