Skip to content

Instantly share code, notes, and snippets.

@pcgeek86
Created September 14, 2019 22:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcgeek86/d1de9b3229194b20c6cdaa7d9bbc2e62 to your computer and use it in GitHub Desktop.
Save pcgeek86/d1de9b3229194b20c6cdaa7d9bbc2e62 to your computer and use it in GitHub Desktop.
Apply 24-bit colors to your text using PowerShell and ANSI escape sequences
while ($true) {
$Red = Get-Random -SetSeed (Get-Date).Ticks.ToString().Substring(10,8) -Maximum 255
$Green = Get-Random -SetSeed (Get-Date).Ticks.ToString().Substring(10,8) -Maximum 255
$Blue = Get-Random -SetSeed (Get-Date).Ticks.ToString().Substring(10,8) -Maximum 255
Write-Host -Object ("$([char]27)[38;2;{0};{1};{2}mtrevor" -f $Red, $Green, $Blue)
}
@nopeless
Copy link

nopeless commented Feb 7, 2024

function Get-TerminalColorEscapeSequence {
    param (
        [string]$HexColor,
        [switch]$Background
    )

    # Remove any leading '#' if present
    $HexColor = $HexColor -replace '^#'

    # Validate hex color code
    if ($HexColor -match '^[0-9A-Fa-f]{6}$') {
        # Convert hex to RGB
        $Red = [convert]::ToByte($HexColor.Substring(0, 2), 16)
        $Green = [convert]::ToByte($HexColor.Substring(2, 2), 16)
        $Blue = [convert]::ToByte($HexColor.Substring(4, 2), 16)

        # Determine if setting foreground or background
        $colorType = if ($Background.IsPresent) { 48 } else { 38 }

        # Generate ANSI color escape sequence
        $EscapeSequence = ([char] 27) + [string]::Format('[{0};2;{1};{2};{3}m', $colorType, $Red, $Green, $Blue)

        # Return the escape sequence
        return $EscapeSequence
    }
    else {
        Write-Host "Invalid hex color code. Please provide a 6-digit hex color code." -ForegroundColor Red
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment