0

所以我写了一个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)

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

谢谢!

4

1 回答 1

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循环内的变量。

于 2013-10-10T18:05:29.703 回答