[英]PowerShell - XML Array Issue
因此,我編寫了一個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)
但是我似乎無法使其正常工作。 關於如何為數組中的每個節點寫出具有一個數組位置的每一行的任何想法?
謝謝!
就像@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
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.