Advertisement
Guest User

Write-ANSI.psm1

a guest
Jul 7th, 2017
1,012
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # easy reference ANSI sequence. remember to reference as ${ANSI} to avoid colliding
  2. # with surrounding text
  3. $ANSI = "$([char](0x1B))["
  4.  
  5.  
  6. function Write-ANSI {
  7.     [CmdletBinding()]
  8.     param(
  9.         [string]$Message
  10.     )
  11.    
  12.     # extract the numeric portion of each "{:*:}" notated piece
  13.     $ANSICodePieces = ([regex]::Matches($Message, "(?<={:).*?(?=:})")).Value
  14.    
  15.     # process each piece in turn
  16.     foreach ($acp in $ANSICodePieces) {
  17.        
  18.         switch ($acp) {
  19.             { $_ -match "" } {
  20.                 # reset block, {::}
  21.                 $ANSIColorCode = "${ANSI}0m"
  22.             }
  23.             {$_ -match "^,([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"} {
  24.                 # background color block, {:,#:}
  25.                 $ANSIColorCode = "${ANSI}48;5;$($acp -replace ',','')m"
  26.             }
  27.             {$_ -match "^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]),([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"} {
  28.                 # foreground and background color block, {:#,#:}
  29.                 $colorCodes = $acp -split ","
  30.                 $ANSIColorCode = "${ANSI}38;5;$($colorCodes[0])m${ANSI}48;5;$($colorCodes[1])m"
  31.             }
  32.             {$_ -match "^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"} {
  33.                 # foreground color block, {:#:}
  34.                 $ANSIColorCode = "${ANSI}38;5;${acp}m"
  35.             }
  36.             default {
  37.                 throw "unsupported ANSI color code block"
  38.             }
  39.         }
  40.        
  41.         # reconstruct the entire notation and replace it with the full ANSI code piece
  42.         $Message = $Message -replace "{:${acp}:}", $ANSIColorCode
  43.        
  44.     }
  45.    
  46.     # reset the color at the end of every message regardless, otherwise your
  47.     # prompt or other output could become tainted
  48.     $Message += "${ANSI}0m"
  49.    
  50.     # actually write the information to screen
  51.     Write-Information -MessageData $Message -InformationAction Continue
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement