convertto-herestring for xml and html with embedded powershell variables

Using double quoted here-strings in Powershell as a method of including and expanding Powershell variables within HTML or XML has been discussed in a few other blogs, and is an excellent way to create HTML or XML documents with variablized values and use them for document or report templates.

The two methods I’ve seen discussed for doing this are to either include the here-string in the script, or to wrap the HTML or XML in @” and  “@, give it a .ps1 file extension, and then dot-source that script within another script that’s setting the values of the variables to be expanded.  While both of these methods work, they don’t provide an easy way to use the HTML or XML files directly.  What’s missing is a convertto-herestring.

Creating a here-string relatively easy –

start with  @” followed immediatly by a newline

add each line of the here-string followed by a newline

end with “@ and a newline.

You can script that.

$xmlfile = “c:\myxmlfiles\myfile.xml”

 invoke-expression (‘@”‘ + “`n” + (get-content $xmlfile | foreach-object  {$_ + “`n”}) + ‘”@’)

Now, that’s not the prettiest thing to code or look at in the middle of a script.  You can make it a function, and then just pipe your file contents to it:

function convertto-herestring {
begin {$temp_h_string = ‘@”‘ + “`n”}
process {$temp_h_string += $_ + “`n”}
end {
    $temp_h_string += ‘”@’
    iex $temp_h_string

$xmlfile = “c:\myxmlfiles\myfile.xml”

[xml]$xml_doc = gc $xmlfile | convertto-herestring

and then you can just imbed your Powershell variable names in your XML or HTML template docs using your favorite edit program. Pipe the contents of that file through convertto-herestring, and it will emit that XML (or HTML) with all the powershell variable expanded.  Just be sure to have all of the named variables that are in your template file defined in your script before you create your here-string.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s