Power$nippets

Boost your shell with reusable code stripped to its essentials

ConvertFrom-SourceTable

At first sight, all most every PowerShell developer would say that it is not purposed to restore an object list from a Format-Table output, but if you think out of the box, I would say: “why not?”.
The Format-Table output has a few quirks, but in general, a fixed-width table -which I would like to call aSourceTable– are most easy to read by human and can actually still be interpreted by a program. A very nice example is the following color table:

Name       Value         RGB
----       -----         ---
Black   0x000000       0,0,0
White   0xFFFFFF 255,255,255
Red     0xFF0000     255,0,0
Lime    0x00FF00     0,255,0
Blue    0x0000FF     0,0,255
Yellow  0xFFFF00   255,255,0
Cyan    0x00FFFF   0,255,255
Magenta 0xFF00FF   255,0,255
Silver  0xC0C0C0 192,192,192
Gray    0x808080 128,128,128
Maroon  0x800000     128,0,0
Olive   0x808000   128,128,0
Green   0x008000     0,128,0
Purple  0x800080   128,0,128
Teal    0x008080   0,128,128
Navy    0x000080     0,0,128

So, what is the catch?
In most cases the boundaries of the table columns can be determined from the header, ruler and data but in some cases it is undefinable because some table layouts, as Format-Table, might contain left- and right aligned columns and not enough data to determine the borders of the column:

City                   Phone
----                   -----
Pennsylvania 1 212 736 5000

Apart from this (which can be quiet easily resolved by replacing or providing a better ruler), there aren’t many other downsides to a SourceTable. Besides, if we consider centered column alignments as unsupported, an extra feature can taken in the SourceTable concept:

  • Every left aligned field will be considered as a string
  • Every right aligned field will be interpreted as an expression

In a lot of cases, values other than a string, e.g. numbers, are already right aligned by programs (and cmdlets like Format-Table) but unfortunately it is not (yet) done to an extend were even value types like arrays are right aligned and formatted for direct interpretation, like the RGB column in the color table example were the hexadecimal value column is parsed to an integer and the RGB column to an array. This feature gives an advantage to a CSV formatted table which only support strings and to a Xml formatted table which is very verbose and therefore hard to read.

A SourceTable is intended for relative small tables and could be easily embedded together with the source code. In the future it might support multi-line fields and also have a PowerShell ConvertTo-SourceTable cmdlet to automatically create advanced source tables.

Last updated on 4 Jun 2020
Published on 4 Jun 2020