2013-10-10 32 views
0

因此,我編寫了一個PowerShell腳本來讀取xml文件,解析並清理後輸出到文件。我的問題是,當它通過foreach循環循環時,它將全部存儲到相同的變量中。PowerShell - XML Array Issue

#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) 

但我似乎無法得到它的工作。有關如何使用陣列中每個節點的一個數組位置寫出每行的任何想法?

謝謝!

+2

請添加一個輸入樣本,以便我們可以看到架構。 – Eris

回答

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的循環中的變量屬性。