Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # easy reference ANSI sequence. remember to reference as ${ANSI} to avoid colliding
- # with surrounding text
- $ANSI = "$([char](0x1B))["
- function Write-ANSI {
- [CmdletBinding()]
- param(
- [string]$Message
- )
- # extract the numeric portion of each "{:*:}" notated piece
- $ANSICodePieces = ([regex]::Matches($Message, "(?<={:).*?(?=:})")).Value
- # process each piece in turn
- foreach ($acp in $ANSICodePieces) {
- switch ($acp) {
- { $_ -match "" } {
- # reset block, {::}
- $ANSIColorCode = "${ANSI}0m"
- }
- {$_ -match "^,([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"} {
- # background color block, {:,#:}
- $ANSIColorCode = "${ANSI}48;5;$($acp -replace ',','')m"
- }
- {$_ -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])$"} {
- # foreground and background color block, {:#,#:}
- $colorCodes = $acp -split ","
- $ANSIColorCode = "${ANSI}38;5;$($colorCodes[0])m${ANSI}48;5;$($colorCodes[1])m"
- }
- {$_ -match "^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"} {
- # foreground color block, {:#:}
- $ANSIColorCode = "${ANSI}38;5;${acp}m"
- }
- default {
- throw "unsupported ANSI color code block"
- }
- }
- # reconstruct the entire notation and replace it with the full ANSI code piece
- $Message = $Message -replace "{:${acp}:}", $ANSIColorCode
- }
- # reset the color at the end of every message regardless, otherwise your
- # prompt or other output could become tainted
- $Message += "${ANSI}0m"
- # actually write the information to screen
- Write-Information -MessageData $Message -InformationAction Continue
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement