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
Labels: powershell, windows
October 2007 November 2007 December 2007 January 2008 February 2008 April 2008 October 2009
Subscribe to Posts [Atom]