This week I was fortunate to attend the inaugural PowerShell Summit. Among the various sessions, Jeffrey Hicks presented on conditional HTML formatting with PowerShell. The native mdlet does a nice job converting objects to HTML tables, but has no support for applying custom styles to individual table elements.
Jeff called out the clever idea of using
ConvertTo-HTML to generate
XHTML, then using PoSH to manipulate that as XML. Jeff’s
technique uses the standard PoSH object model to apply CSS styles to
rows. In my case, I had a table where I needed to apply formatting to
individual cell entries (TD elements). Further complicating things,
rather than testing a single column, any cell entry with a particular
value (in my case, a value of ‘False’) was one I needed to flag with my
style. Referencing cell values via the object model wasn’t returning a
simple value that I could modified. What to do?
The answer, it turns out, is to call upon an old foe of mine,
XPATH. After much wailing and
gnashing of teeth, a simple query of
wound up being the magic incantation. Piping this to a foreach loop let
me append an XML attribute which I could then append to each of the TD
elements returned from the query. A quick dump of the object via
$html.innerxml and, as they say, “Bob’s your uncle!”
Yes, it’s a simple technique, but one that foiled me for a couple of days – I did say that XPATH is my nemesis, right?