<# .SYNOPSIS Provides possibility to colorize text in console using ANSI sequences. #> using namespace System.Drawing function ToColor { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)] [ValidateNotNullOrEmpty()] [object] $ColorInput ) if ($ColorInput -is [Color]) { return $ColorInput } if ($ColorInput -is [string]) { if ($ColorInput -imatch '^[a-z]+$') { return [System.Drawing.Color]::FromName($ColorInput) } if ($ColorInput -match '^#([0-9A-F]{3}|[0-9A-F]{6})$') { return [System.Drawing.ColorTranslator]::FromHtml($ColorInput) } } throw "Could not convert the value `"$ColorInput`" of type `"$($ColorInput.GetType().FullName)`" to Color" } <# .SYNOPSIS Colorizes text using ANSI console feature. .PARAMETER Text String text to colorize. .PARAMETER ForecroundColor Foreground color to be applied to the Text. Can be a color name, hex value (#112233), or System.Drawing.Color. .PARAMETER BackgroundColor Background color to be applied to the Text. Can be a color name, hex value (#112233), or System.Drawing.Color. .EXAMPLE # Returns the string "Alarma" wrapped with ANSI color sequences. Set-TextAnsiCodes 'Alarma' -ForecroundColor 'LightYellow' -BackgroundColor 'DarkGreen' .EXAMPLE # A bit more complex output with aliases: "Value: $(AnsiTxt 56 -fc '#eeaaaa' -bc '#884444')`nCount: $(AnsiTxt 123 -fc '#aaeeaa' -bc '#448844')" #> function Set-TextAnsiCodes { [CmdletBinding()] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string] $Text, [Alias("fc")] [Parameter(Position = 1)] [object]$ForecroundColor, [Alias("bc")] [Parameter(Position = 2)] [object]$BackgroundColor, [Alias("r")] [Parameter()] [switch] $Reversed, [Alias("b")] [Parameter()] [switch] $Bold, [Alias("u")] [Parameter()] [switch] $Underline ) begin { if ($ForecroundColor) { $ForecroundColor = ToColor $ForecroundColor } if ($BackgroundColor) { $BackgroundColor = ToColor $BackgroundColor } } process { $Esc = [char]27 $Terminate = "$Esc[0m" if ($ForecroundColor) { $pre = "$Esc[38;2;$($ForecroundColor.R);$($ForecroundColor.G);$($ForecroundColor.B)m" $Text = "$pre$Text$Terminate" } if ($BackgroundColor) { $pre = "$Esc[48;2;$($BackgroundColor.R);$($BackgroundColor.G);$($BackgroundColor.B)m" $Text = "$pre$Text$Terminate" } if ($Reversed) { $pre = "$Esc[7m" $Text = "$pre$Text$Terminate" } if ($Bold) { $pre = "$Esc[1m" $Text = "$pre$Text$Terminate" } if ($Underline) { $pre = "$Esc[4m" $Text = "$pre$Text$Terminate" } $Text } end { } } function Remove-TextAnsiCodes { [CmdletBinding()] param( [Parameter(Mandatory, Position = 0)] [string] $Text ) $Text -replace "\x1b\[[\w;]+m", "" } Set-Alias "AnsiTxt" Set-TextAnsiCodes Export-ModuleMember -Function ToColor,Set-TextAnsiCodes,Remove-TextAnsiCodes -Alias AnsiTxt