Powershell loop through xml to create a jagged arr

2019-09-18 16:55发布

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条回答
对你真心纯属浪费
2楼-- · 2019-09-18 17:35

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} 
查看更多
登录 后发表回答