Variable / String Appends in Powershell

campbell1972 used Ask the Experts™
I'm in the process of building a PowerShell script which is making heavy use of ConvertTo-HTML to serve as the basis for a web-based reporting tool.

However, I've hit a brick wall with regard to how variables may be appended.

The script sometimes breaks out into a loop when multiple databases need to be interrogated. For  the first database, the HTML is built for the result set as a variable with the last script action being "ConvertTo-HTML  xxxxxx | Output-String".

For the second and subsequent databases, I simply want to append the output to the existing variable.

Any pointers greatly appreciated!
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
PowerShell Developer
Top Expert 2010
ConvertTo-Html will create a standalone HTML document. Added information to that is tricky once it's created. However, that would be a poor way to go about things.

ConvertTo-Html has a Fragment parameter. This generates a table out of an object.

Typically this means you can build a complex document like this:
$body = '<h1>Title 1</h1>'
$body += $results1 | ConvertTo-Html -Fragment
$body += '<h1>Title 2</h1>
$body += $results2 | ConvertTo-Html -Fragment

$document = ConvertTo-Html -Body $body | Out-String

Open in new window

You would often add a head (style information) at the same time. The point of the last step is only to create the wrapper document.

This will leave an empty table in the document, this can be problematic if you have particular styles in use. The Empty table can be removed like this:
$document = $document -replace '<table>\r?\n</table>'

Open in new window

Chris DentPowerShell Developer
Top Expert 2010
Addendum, if the intent is to push everything into a single table, you need to merge everything before ConvertTo-Html is called. Appending information to existing HTML tables would be painful.


Great tips Chris, thanks very much for that!

I can see exactly how I need to go about this now.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial