Creating XML Configuration Files the PowerShell Way.

Several weeks ago I posted an entry on creating configuration files. This same technique can also work with XML files. I’m still working on a more advanced technique but wanted to share this simpler approach.  First, here’s a sample XML configuration file:

#Sample configuration template
#this is for demonstration purposes and proof of concept
        <Computer Help="Enter a computername">{0}</Computer>
        <IP Help="Enter an IPv4 Address">{1}</IP>
        <Subnet Help="Enter an IPv4 SubnetMask">{2}</Subnet>
        <Gateway Help="Enter the default gateway">{3}</Gateway>
            <DNSServer Help="Enter the primary DNS Server">{4}</DNSServer>
            <DNSServer Help="Enter the secondary DNS Server">{5}</DNSServer>
            <Comment Help="Enter a comment">{6}</Comment>
        <Update help="Enter True or False to enable FOO">
                <City help="Enter a city name">{8}</City>
                <CostCenter help="Enter a cost center">{9}</CostCenter>

The XML is contained within a here string in a PowerShell script. Notice the placeholders like {0} and {1}. I’ll use the  -f operator to fill in the blanks. To make this more interesting, I’m going to pull the data from a CSV file.

SERVERA,,,,,,"Sample configuration",TRUE,Tacoma,87321

To create the XML configuration file I’ll need to get these values and merge them with the XML in DemoXMLConfig.ps1. I put together a short script to handle that.

#define XML configuration template
#define the name of the xml file to create
#let's create a custom object that has the values we 
#need for the XML file pulled from a CSV file.
$data=Import-Csv c:\scripts\posh\xmlconfigdata.csv
[xml]$x=(&$config) -f $data.Computername,$data.IP,$data.subnet,$data.gateway,$data.PrimaryDNS,$data.SecondaryDNS,$data.comment,$data.enable,$,$data.CostCenter

The data from the CSV file is imported using Import-CSV and saved to $data. I then “execute” the here string script and use -f to replace placeholders with corresponding values from $data. The output is an XML file so I’ll save it to a variable, $x, specifically cast as an [XML] object. This step is important because in the last line I call the Save() method which commits the XML in memory to a file. Just like that I have a valid XML document ready to use.

It’s not too hard to have a CSV file with several lines and creating multiple XML documents in a matter of seconds.

If you want to try this out yourself you can download a zip file with these samples here.