While at work, one of my coworkers was attempting to read a XML file with powershell, and couldn’t get it to work.
After looking at it a moment, it dawned on me of a way to have server lists that one can use for automation.
Let us say you have a XML file like the following:
<?xml version=”1.0″ encoding=”utf-16″ ?>
<Objs Version=”1.1.0.1″ xmlns=”http://schemas.microsoft.com/powershell/2004/04″>
<DataCenter1>
<FrontEnd>
<Servers>webserver1</Servers>
<Servers>webserver2</Servers>
<Servers>webserver3</Servers>
</FrontEnd>
<BackEnd>
<Servers>datalayer1</Servers>
<Servers>datalayer2</Servers>
</BackEnd>
</DataCenter1>
</Objs>
This is a very simple XML file, that one might use to tell the difference between the front end systems and the back end systems in a datacenter.
Now, how would you load this into powershell?
PS C:\Powershell> [xml]$Servers = gc .\servers.xml
Once that is done, you can now grab things from the XML loaded into $Servers.
PS C:\Powershell> $Servers.Objs.DataCenter1.FrontEnd.Servers
webserver1
webserver2
webserver3
As you can see, this gave me the list of servers under the FrontEnd element.
So to use this, in a foreach loop for example, just do the following foreach.
foreach($Server in $Servers.Objs.DataCenter1.FrontEnd.Servers)
{
Write-Host "$Server is a Front End Server."
}
foreach($Server in $Servers.Objs.DataCenter1.BackEnd.Servers)
{
Write-Host "$Server is a Back End Server."
}
This will give you the following.
webserver1 is a Front End Server.
webserver2 is a Front End Server.
webserver3 is a Front End Server.
datalayer1 is a Back End Server.
datalayer2 is a Back End Server.
Very basic XML usage, but it was enough to give my co-worker a running start.
Later
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.