PowerShell - XML数组问题

时间:2013-10-10 17:15:20

标签: xml arrays powershell

所以我写了一个powershell脚本来读取xml文件,解析它,并在清理完后输出到文件。我的问题是,当它循环遍历foreach循环时,它将所有内容存储到相同的变量中。

#Access the XML file
[xml]$XML= [xml](Get-Content $XmlPath)

foreach ($node in $XML.catalog.entry)
{
    #XML Variables
    $Username = $XML.catalog.entry.username 
    $Description = $XML.catalog.entry.description
    $Service = $XML.catalog.entry.service

    #Creating the syslog event that will be sent to SecureVue
    $writeOutput= "Username : [$Username] Description: [$Description] Service: [$Service]"

    #output
    $writeOutput
}

不幸的是,我继续得到它的输出:

Username : [User1 User2 User3 User4] Description: [Description1 Description2 Description3 Description4] Service: [Service1 Service2 Service3 Service4]
Username : [User1 User2 User3 User4] Description: [Description1 Description2 Description3 Description4] Service: [Service1 Service2 Service3 Service4]
Username : [User1 User2 User3 User4] Description: [Description1 Description2 Description3 Description4] Service: [Service1 Service2 Service3 Service4]
Username : [User1 User2 User3 User4] Description: [Description1 Description2 Description3 Description4] Service: [Service1 Service2 Service3 Service4]

而不是:

Username : [User1] Description: [Description1] Service: [Service1]
Username : [User2] Description: [Description2] Service: [Service2]
Username : [User3] Description: [Description3] Service: [Service3]
Username : [User4] Description: [Description4] Service: [Service4]

我知道我需要一些变体:

foreach($node in $XML.ChildNodes)

但我似乎无法让它发挥作用。关于如何使用数组中每个节点的一个数组位置写出每一行的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

正如@Eris所说,XML文件的一个示例会使这更容易测试,但一眼就看出,这部分可能是一个很好的起点:

foreach ($node in $XML.catalog.entry)
{
    #XML Variables
    $Username = $XML.catalog.entry.username 
    $Description = $XML.catalog.entry.description
    $Service = $XML.catalog.entry.service

    ...
}

当您的意图可能分配各个节点的属性时,看起来您正在分配节点集合的这些变量属性。我会尝试这样的事情,而不是:

foreach ($node in $XML.catalog.entry)
{
    #XML Variables
    $Username = $node.username 
    $Description = $node.description
    $Service = $node.service

    ...
}

即。对于循环内部的变量,您需要$node的属性,而不是$XML.catalog.entry