Powershell loop through xml to create a jagged array

橙三吉。 提交于 2019-12-12 03:48:50

问题


I'm guessing this is pretty simple, I'm just starting with powershell and I can't seem to find a simple solution after a few hours searching the net.

Basically I have the following xml file

<Config>
<System>
<Server>
    <Name>host1</Name> 
    <Service>service1</Service>
    <Service>service2</Service>
</Server>
<Server>
    <Name>host2</Name> 
    <Service>service1</Service>
</Server>
</System>

<System2>
<Server>
    <Name>host1</Name> 
    <Service>service1</Service>
    <Service>service2</Service>
</Server>
<Server>
    <Name>host2</Name> 
    <Service>service1</Service>
     <Service>service2</Service>
     <Service>service3</Service>

</Server>
</System2>
</Config>

And I would like to get the contents into a jagged 2d array, so system would wind up as follows:

  • (host1),(service1,service2)
  • (host2),(service1)

Is it possible to iterate through each element and create such an array?

I'm hoping to store the data as above so that I can use [0][0] to reference the hostname and then [1][1..x] to reference all services for that host.

Does that make any sense?

Any help or better appraoch is greatly appreciated.


回答1:


You might think about using a hashtable for this instead. You can still iterate over the results and you can look up results by hostname e.g.:

$xml = [xml]@'
    <Config>
    <System>
    <Server>
        <Name>host1</Name> 
        <Service>service1</Service>
        <Service>service2</Service>
    </Server>
    <Server>
        <Name>host2</Name> 
        <Service>service1</Service>
    </Server>
    </System>

    <System2>
    <Server>
        <Name>host1</Name> 
        <Service>service1</Service>
        <Service>service2</Service>
    </Server>
    <Server>
        <Name>host2</Name> 
        <Service>service1</Service>
        <Service>service2</Service>
        <Service>service3</Service>
    </Server>
    </System2>
    </Config>
'@

$ht = @{}
$hostnameNodes = $xml | Select-Xml -XPath '//Name'
foreach ($node in @($xml | Select-Xml -XPath '//Name'))
{
    $hostname = $node.Node.InnerText.Trim()
    $services = @($node.Node.ParentNode.Service)
    foreach ($service in $services)
    {
        $ht["$hostname"] += @($service.Trim())
    }
}

$ht

Outputs:

Name                           Value                                    
----                           -----                                    
host1                          {service1, service2, service1, service2} 
host2                          {service1, service1, service2, service3} 


来源:https://stackoverflow.com/questions/13919548/powershell-loop-through-xml-to-create-a-jagged-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!