Home > powershell, windows > Powershell and XML Configuration Files

Powershell and XML Configuration Files

 

One of the things that I almost always create when I am developing a script is a configuration file. Utilizing XML for a configuration file format is very easy with Powershell.  The first thing that you need to do is to layout your XML file. I typically don’t create a DTD or verify the XML schema because well, only my scripts will be using the XML configuration file.  Not completely within spec, but I’ve learn to live with it. The XML does need to be well formed with proper closing brackets, root node, etc in order for Powershell to read the XML but that is the only restriction.

The most common XML file that I create includes a list of servers and some attribute about those servers. A simple  example that of a test application that is made up of three web servers and a database server. The way that I would create the XML would be as follows:

<test_app_servers>
    <dbs server=”vm-dbs1″ dbsname=”eut”/>
    <web dir=”d$\inetpub\wwwroot”>
        <server>vm-test1</server>
        <server>vm-test2</server>
        <server>vm-test3</server>
    </web></test_app_servers>

Now the important part, how does Powershell read the XML.  The code is very straight forward. You use the get-content command and cast the file as XML.  The command is:

$cfgFile = “.\test_app_config.xml”
$root = “test_app_servers”
$cfg = [xml] ( gc $cfgFile )

Now once you have the configuration saved in the variable $cfg then how do you use it?  Powershell stores the information in a tree format so it is easy to get at. Some samples of how to get at the data include:

$strDbsName = $cfg.$root.dbs.dbsname

$strDbsServer = $cfg.$root.dbs.server

$strWebDir = $cfg.$root.web.dir

$cfg.$root.web.server | % {
        $strWebServer = $_
        “Content of
\\$strWebServer\$strWebDir
        dir
\\$strWebServer\$strWebDir

}

And that is all you should need to know in order to utilize XML as a configuration file with Powershell

Categories: powershell, windows
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.