Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created August 10, 2023 04:40
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 Jaykul/9999be71ee68f3036dc2529c451729f4 to your computer and use it in GitHub Desktop.
Save Jaykul/9999be71ee68f3036dc2529c451729f4 to your computer and use it in GitHub Desktop.

When I'm having a bad day, I can spend hours just fiddling with colors and recursion ...

Today I wrote an HslEnumerator class which is fun because if you output it to the PowerShell terminal it just goes on producing colors forever:

[HslEnumerator][PoshCode.Pansies.RgbColor]"Goldenrod" | Format-Wide 30 # I do have a wide screen

But I also made something more fun. Out-Colors will colorize tables or lists with fun HSL rainbows...

Screenshot of Get-Command -Module Pansies | Format-Table | Out-Colors

#requires -Modules Pansies
using namespace System
using namespace System.IO
using namespace System.Collections
using namespace System.Collections.Generic
using namespace System.Linq
class HslEnumerator : IEnumerator[PoshCode.Pansies.RgbColor] {
hidden [PoshCode.Pansies.RgbColor]$Start = "White"
[int]$HueStep = 1
[int]$LightStep = 1
[int]$SatStep = 1
# Default constructor so we can cast hashtables
HslEnumerator() {}
HslEnumerator([PoshCode.Pansies.RgbColor]$Start) {
$this.Start = $Start
}
# Implement IEnumerator.
[PoshCode.Pansies.RgbColor]$Current = $null
[object] get_Current() {
return $this.Current
}
[bool] MoveNext() {
if ($null -eq $this.Current) {
$this.Current = $this.Start
return $true
}
$next = $this.Current.ToHsl();
$next.H += $this.HueStep;
$next.H %= 360;
if ($next.S + $this.SatStep -gt 100) {
$next.S = 20;
} else {
$next.S += $this.SatStep;
}
if ($next.L + $this.LightStep -gt 80) {
$next.L = 20;
} else {
$next.L += $this.LightStep
}
$this.Current = $next.ToRgb();
return $true;
}
[void] Reset() {
$this.Current = $null;
}
# IDisposable is required by IEnumerator
[void] Dispose() {}
}
filter Out-Colors {
[CmdletBinding()]
param(
[HslEnumerator]$Colors = @{ Start = "GoldenRod"; HueStep = 18},
[Parameter(ValueFromPipeline)]
$FormatInfoData
)
# Only color the data (not the headers)
if ($_.GetType().Name -eq "FormatEntryData") {
# Listview
@($_.FormatEntryInfo.ListViewFieldList).Where{ $_ }.ForEach{
$null = $Colors.MoveNext()
$_.FormatPropertyField.propertyValue = $Colors.Current.ToVt() + $_.FormatPropertyField.propertyValue
}
# Tableview
@($_.FormatEntryInfo.FormatPropertyFieldList).Where{ $_ }.ForEach{
$null = $Colors.MoveNext()
$_.propertyValue = $Colors.Current.ToVt() + $_.propertyValue
}
}
# Pass through everything
$_
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment