Life in a colour – part 2. :)

OK, it’s not fine and tuned and it uses regex for simple task, and it’s slow, BUT – it works! 🙂

Most of time, of course: as long as your column names are left-aligned. And it also kills pipe, so it has to be improved! 😉

Results first:

Out-colour-columnsNice, colourful output. You decide which colours to use, how many of them will be displayed, in which order. It is all up to you! 🙂

Code:

PowerShell, using GeSHi 1.0.8.8
  1. function outcolour {
  2.         if ($Input) {
  3.                 [int[]]$columns = @()
  4.                 # select colours you prefer and the one that a readable on your console.. 🙂
  5.                 $colours = @(‘Magenta’,‘Yellow’,‘Cyan’,‘Green’)
  6.                 foreach ($obj in ($Input | Out-String -Stream)) {
  7.                         if ($columns.count -eq 0) {
  8.                                 $match = $obj | Select-String AllMatches -Pattern ‘[^|s]-{2,}’ | Select-Object -ExpandProperty Matches
  9.                                 if ( ($match | Measure-Object | Select-Object -ExpandProperty Count) -ge 2) {
  10.                                         $columns = $match | Select-Object -ExpandProperty Index
  11.                                 }
  12.                                 Write-Host $obj
  13.                         } else {
  14.                                 foreach ($char in $obj.ToCharArray()) {
  15.                                         $colour = $null
  16.                                         $X = $Host.UI.RawUI.CursorPosition.X
  17.                                         for ($i=0; $i -lt $columns.count 1; $i++) {
  18.                                                 Write-Verbose "i = $i ; X = $X"
  19.                                                 if ( ( $X -ge $columns[$i]) -and ( $X -lt $columns[$i+1] ) ) {
  20.                                                         $colour = $colours[($i % $colours.count)]
  21.                                                 }
  22.                                         }
  23.                                         if (!$colour) {
  24.                                                 $colour = $colours[(($columns.count 1) % $colours.count)]
  25.                                         }
  26.                                         Write-Host -ForegroundColor $colour $char -NoNewline
  27.                                 }
  28.                         "`r"
  29.                         }
  30.                 }
  31.         }
  32. }

It was fun to write it, and fun to play with it! 🙂 PowerShell is Ring of Power for sure! Wonder if I become a Nazgul one day… 😉

1 thought on “Life in a colour – part 2. :)

  1. Hi,

    Very nice script, but is does not work with grouped output, like from Get-ChildItem -Recurse. It will colour the headers for the next group as well.

    (Speed could be better as well)

    Remco

Leave a comment